Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 2:

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CS 307 Fundamentals of Computer ScienceReferences and Object Variables 1 Topic 3 References and Object Variables "Thou shalt not follow the NULL pointer,
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
OOP Languages: Java vs C++
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
Basic Semantics Associating meaning with language entities.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
C++ Memory Overview 4 major memory segments Key differences from Java
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new.
Slide 1 Chapter 10 Pointers and Dynamic Arrays. Slide 2 Learning Objectives  Pointers  Pointer variables  Memory management  Dynamic Arrays  Creating.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
Pointers and Dynamic Arrays
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Chapter 10 Pointers and Dynamic Arrays. Learning Objectives Pointers – Pointer variables – Memory management Dynamic Arrays – Creating and using – Pointer.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Static arrays.
Object-Oriented Programming Chapter Chapter
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
CS 152: Programming Language Paradigms March 19 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Design issues for Object-Oriented Languages
Object Lifetime and Pointers
Dynamic Storage Allocation
Pointers and Dynamic Arrays
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Java Primer 1: Types, Classes and Operators
Advanced Program Design with C++
COMP 2710 Software Construction Pointers
Pointers Revisited What is variable address, name, value?
Dynamic Memory Allocation
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
9-10 Classes: A Deeper Look.
Dynamic Memory.
Java Programming Language
Introduction to Data Structures and Software Engineering
9-10 Classes: A Deeper Look.
Presentation transcript:

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 2: Data types Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style DATA TYPES Simple data types Pointers Type checking Type coercion Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Highly similar to Java data types Basic types are not classes (like Java) Pit trap: different compilers will have different ranges for most basic data types Some programs potentially will behave differently across different platforms Hence, lack of portability of C++ programs User-defined data types using struct (as in C), as well as class (object-oriented programming) Both are allowed in the same program In fact, they are almost equivalent, but struct was kept for backward compatibility A struct can have data members, methods, constructors, destructors, etc One difference is that a struct sets its members as public by default Data types Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Data types: simple types size, range and precision Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Data types: simple types size, range and precision Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering A variable can be declared for any type valid in the current scope. int x; double y; myClass mc; Multiple variables of the same type can be declared on the same declaration: int x,y,z; Any declared name can be referred to thereafter in the scope in which it is declared. Variable declaration Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Declarations can include an optional initialization, which can use different syntactical forms: Type a1 {v}; Type a2 = {v}; Type a3 = v; Type a4(v); All of these are widely used and apparently equivalent. However: Some are restricted to use in certain situations. Only the first one is universally usable, and is actually safer, as it implicitly does some checking of the value passed versus the specified type. int a1 = 1.5; //allowed using truncation int a1 {1.5}; //not allowed, as truncation would happen Variable declaration Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering C++ uses a manifest typing strategy Variables and values have types Values can only be assigned to variables declared as having the same type However, C++ allows type coercion, i.e. implicitly or explicitly changing the type of variables or values This loophole, among other things, makes C++ a weakly typed language Type mismatches General Rule: Cannot place value of one type into variable of another type intVar = 2.99;// 2 is assigned to intVar! Only integer part "fits", so that’s all that goes Called "implicit type casting" or "automatic type conversion" When using pointers or classes, much more problematic! Data types: type checking and type coercion Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Literals 2, 5.75, ‘Z’, "Hello World“ Considered "constants": can’t change in program All literals have an inherent type that can be determined during lexical analysis. Like many other languages, C++ uses escape sequences for string literals: Data types: literals Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Variables contain a specific value, e.g., an integer. Pointer variables hold a memory addresses as their values. A pointer contains the memory address of a portion of memory that in turn contains a specific value. For any type T, T* is the type “pointer to T”, i.e. a variable of type T* can hold the address of an object of type T. int i = 99; int* p = &i; cout << *p << endl; Two operators on pointers: Dereferencing operator: *, e.g. *p refers to the object pointed to by the pointer. Address operator: &, e.g. &i refers to the address of the first memory cell holding an object. Data types: pointer variables Joey Paquet, Advanced Program Design with C++ 99 &i i (int) p (*int)

Concordia University Department of Computer Science and Software Engineering Consider: int *p1, *p2, v1, v2; Pointer assignment: p1 = &v1; Sets pointer variable p1 to "point to" variable v1 " p1 equals address of v1 " Or " p1 points to v1 “ v1 = 0; *p1 = 42; p1 and v1 refer to same memory cell Data types: pointer variables Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Pointer assignment vs value assignment: int v1 = 42; int v2 = 9; int *p2 = &v2; int *p1 = &v1; Pointer assignment: p2 = p1; Assigns one pointer to another "Make p2 point to where p1 points“ Value assignment: *p2 = *p1; Assigns "value pointed to" by p1, to "value pointed to" by p2 Data types: pointer variables Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Dynamic variables Allocated with new operator, deallocated with the delete operator Allocated and destroyed explicitly while program runs Local variables Declared within function definition Not dynamic Allocated on the stack when code block is entered (e.g. function call) Destroyed when code block is exited (e.g. function call completes) Often called "automatic" variables Allocation and deallocation controlled for you Data types: pointer variables Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering The operator new creates dynamically allocated values that can then be pointed to by pointer variables. The value created is a nameless pointer value. Allocated on the heap, or freestore through the runtime system’s interaction with the operating system. All dynamically allocated variables need to be carefully managed by the programmer. C++ does not have garbage collection. Dynamically allocated variables need to be allocated and deallocated manually Similar to C’s malloc Data types: pointer variables Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Data types: pointer variables Joey Paquet, Advanced Program Design with C++ int *p1, *p2; p1 = new int; *p1 = 42; p2 = p1;

Concordia University Department of Computer Science and Software Engineering *p2 = 53; *p1 = new int; *p1 = 88; Data types: pointer variables Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering If the type used as parameter is of class type: Constructor is called for new object Can invoke different constructor with initializer arguments: MyClass *myPtr; myPtr = new MyClass(32.0, 17); Can still initialize non-class types: int *n; n = new int(17);//Initializes *n to 17 Data types: pointer variables Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Pointers are full-fledged types Can be used just like other types Can be function parameters Can be returned from functions Example: int* findOtherPointer(int* p); This function declaration: Has "pointer to an int" parameter Returns "pointer to an int" Data types: pointer variables Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Potential problem if freestore runs out of memory Older compilers: Test if null returned by call to new : int *p; p = new int; if (p == NULL) { cout << "Error: Insufficient memory.\n"; exit(1); } Later compilers (C++98 and after) : new throws exception bad_alloc try { int * myarray= new int[1000]; } catch (bad_alloc&) { cout << "Error allocating memory." << endl; } Data types: pointer variables Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering To deallocate dynamic memory, use the delete operator When value no longer needed Returns memory to freestore Example: int *p; p = new int(5); //allocate memory … //Some processing… delete p; //deallocate memory p = NULL; //prevents dangling pointer errors Deallocates dynamic memory "pointed to by pointer p“ p is then a dangling pointer If not deleted before the variable goes out of scope, memory is not freed, which creates a memory leak. Plus, dereferencing a dangling pointer leads to unpredictable results, ranging from getting a seemingly random value to program crash. Managing dangling pointers and deallocating dynamically allocated memory is a very important aspect of proper C++ programming. Data types: pointer variables Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Can perform arithmetic operations on pointers Used to navigate arrays (covered later) Example: int *d; d = new int[10]; d refers to: address of new int[10] d + 1 refers to: address of new int[10] + 1*sizeof(int) d + 2 refers to: address of new int[10] + 2*sizeof(int) d[i] == *(&d[0]+j) == *(a+j) Pointer arithmetic Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style references Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Pointers are very powerful, as they allow: A variable to refer a value held by another variable. A variable to refer to different values held by different variables in time. Pass information around without having to copy it. However, due to their power, pointers bring additional complexities: Must use a special syntax ( *, &, -> ) Possibility of dangling pointers, wild pointers, null pointers. References are pointer variables that eliminate some of the disadvantages of pointers, at the cost of eliminating some of their power. Pointer arithmetic cannot be applied to a reference. Any operation applied to a reference is actually applied onto the variable it refers to, including assignment. Hence, references must be initialized upon declaration and cannot be changed afterwards. Furthermore, given a reference int& r {v1}, &r returns a pointer to the object referred to by r. Thus, we cannot even have a pointer to a reference. Reference Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Click to edit Master title style type casting Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering C++ provides operators for explicit type coercion, or type casting static_cast intVar Explicitly "casts" intVar to double type doubleVar = static_cast intVar1/intVar2; Casting forces double-precision division to take place among two integer variables. Equivalent in meaning to the following C syntax, even though the C++ cast operation is checked at compile time and is thus less prone to runtime errors doubleVar = (double)intVar1/intVar2; Data types: explicit type casting Joey Paquet, COMP Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Data types: explicit type casting Joey Paquet, COMP Advanced Program Design with C++ Different kinds of explicit type casting operations: static_cast (expression) General-purpose type casting const_cast (expression) Cast-out “constantness” dynamic_cast (expression) Runtime-checked conversion of pointers and references within a single class hierarchy. Used for downcasting from a superclass to a subclass reinterpret_cast (expression) Implementation-dependent casting, performs a binary copy and assigns the new type to the resulting binary copied value. Highly unsafe and error-prone.

Concordia University Department of Computer Science and Software Engineering When dealing with classes and subclasses, one can declare objects of a supertype and manipulate them as one of its subclasses Problem: subclass members are undefined in superclass Data types: upcasting and downcasting Joey Paquet, Advanced Program Design with C++ GeometricObject area perimeter Circle radius diameter Rectangle width height void displayGeometricObject(GeometricObject& g) { cout << "The radius is " << g.getRadius() << endl; cout << "The diameter is " << g.getDiameter() << endl; cout << "The width is " << g.getWidth() << endl; cout << "The height is " << g.getHeight() << endl; cout << "The area is " << g.getArea() << endl; cout << "The perimeter is " << g.getPerimeter() << endl; }

Concordia University Department of Computer Science and Software Engineering May want to use static_cast : This successfully compiles, but will fail at runtime if the object passed was originally of a type that does not contain the members referred to in the code. static_cast makes a static (compile-time) type cast, but correct runtime behavior is not verified. Data types: upcasting and downcasting Joey Paquet, Advanced Program Design with C++ void displayGeometricObject(GeometricObject& g) { GeometricObject* p = &g; cout (p)->getRadius() << endl; cout (p)->getDiameter() << endl; cout (p)->getWidth() << endl; cout (p)->getHeight() << endl; cout << "The area is " << g.getArea() << endl; cout << "The perimeter is " << g.getPerimeter() << endl; }

Concordia University Department of Computer Science and Software Engineering Use dynamic_cast to downcast into a subclass dynamic_cast works on pointers Does runtime checking to verify that the cast is successful Also deals with polymorphic types and the virtual methods table at runtime Data types: upcasting and downcasting Joey Paquet, Advanced Program Design with C++

Concordia University Department of Computer Science and Software Engineering Y. Daniel Liang, Introduction to Programming with C++ (Chapter 1, 11, 13, 15), Peason, Bjarne Stroustrup, The C++ Programming Language (Chapter 6, 7, 11, 22), Addison-Wesley, References Joey Paquet, COMP Advanced Program Design with C++