COMP 345 Advanced Program Design with C 1

  • Slides: 30
Download presentation
COMP 345 - Advanced Program Design with C++ 1 Click to edit Master title

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

COMP 345 - Advanced Program Design with C++ 2 Click to edit Master title

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

COMP 345 - Advanced Program Design with C++ 3 Data types • Highly similar

COMP 345 - Advanced Program Design with C++ 3 Data types • 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 Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 4 Data types: simple types size,

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

COMP 345 - Advanced Program Design with C++ 5 Data types: simple types size,

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

Advanced Program Design with C++ 6 Variable declaration • A variable can be declared

Advanced Program Design with C++ 6 Variable declaration • A variable can be declared for any type valid in the current scope. int x; double y; my. Class 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. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 7 Variable declaration • Declarations can include an optional

Advanced Program Design with C++ 7 Variable declaration • Declarations can include an optional initialization, which can use different syntactical forms: Type a 1 {v}; a 2 = {v}; a 3 = v; a 4(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 a 1 = 1. 5; //allowed using truncation int a 1 {1. 5}; //not allowed, as truncation would happen Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 8 Data types: type checking and

COMP 345 - Advanced Program Design with C++ 8 Data types: type checking and type coercion • C++ uses a manifest typing strategy • Variables and values are assigned types explicitly in the source code • 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 int var = 2. 99; // 2 is assigned to var! • Only the 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! Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 9 Data types: literals • Literals

COMP 345 - Advanced Program Design with C++ 9 Data types: literals • 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: Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 10 Data types: pointer variables • Variables contain a

Advanced Program Design with C++ 10 Data types: pointer variables • Variables contain a specific value, e. g. , an integer. • Pointer variables hold 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; i (int) 99 p (*int) &i • 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. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 11 Data types: pointer variables • Consider: int *p

Advanced Program Design with C++ 11 Data types: pointer variables • Consider: int *p 1, *p 2, v 1, v 2; • Pointer assignment: p 1 = &v 1; • Sets pointer variable p 1 to "point to" variable v 1 • "p 1 equals address of v 1" • Or "p 1 points to v 1“ v 1 = 0; *p 1 = 42; • p 1 and v 1 refer to same memory cell Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 12 Data types: pointer variables • Pointer assignment vs

Advanced Program Design with C++ 12 Data types: pointer variables • Pointer assignment vs value assignment: int v 1 = 42; int v 2 = 9; int *p 2 = &v 2; int *p 1 = &v 1; • Pointer assignment: p 2 = p 1; • Assigns one pointer to another • "Make p 2 point to where p 1 points“ • Value assignment: *p 2 = *p 1; • Assigns "value pointed to" by p 1, to "value pointed to" by p 2 Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 13 Data types: pointer variables • Dynamic variables •

Advanced Program Design with C++ 13 Data types: pointer variables • 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 Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 14 Data types: pointer variables • The operator new

Advanced Program Design with C++ 14 Data types: pointer variables • 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 Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 15 Data types: pointer variables int *p 1, *p

Advanced Program Design with C++ 15 Data types: pointer variables int *p 1, *p 2; p 1 = new int; *p 1 = 42; p 2 = p 1; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 16 Data types: pointer variables *p 2 = 53;

Advanced Program Design with C++ 16 Data types: pointer variables *p 2 = 53; *p 1 = new int; *p 1 = 88; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 17 Data types: pointer variables • If the type

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

Advanced Program Design with C++ 18 Data types: pointer variables • Pointers are full-fledged

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

Advanced Program Design with C++ 19 Data types: pointer variables • Potential problem if

Advanced Program Design with C++ 19 Data types: pointer variables • 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; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 20 Data types: pointer variables • To deallocate dynamic

Advanced Program Design with C++ 20 Data types: pointer variables • 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. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 21 Pointer arithmetic • Can perform arithmetic operations on

Advanced Program Design with C++ 21 Pointer arithmetic • 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) Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 22 Click to edit Master title style References Concordia

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

Advanced Program Design with C++ 23 Reference • Pointers are very powerful, as they

Advanced Program Design with C++ 23 Reference • 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 {v 1}, &r returns a pointer to the object referred to by r. Thus, we cannot even have a pointer to a reference. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 24 Click to edit Master title style Type casting

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

COMP 345 - Advanced Program Design with C++ 25 Data types: explicit type casting

COMP 345 - Advanced Program Design with C++ 25 Data types: explicit type casting • C++ provides operators for explicit type coercion, or type casting static_cast<double>int. Var • Explicitly "casts" int. Var to double type double. Var = static_cast<double>int. Var 1/int. Var 2; • 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 double. Var = (double)int. Var 1/int. Var 2; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 26 Data types: explicit type casting

COMP 345 - Advanced Program Design with C++ 26 Data types: explicit type casting • Different kinds of explicit type casting operations: static_cast<Type>(expression) General-purpose type casting const_cast<Type>(expression) Cast-out “constantness” dynamic_cast<Type>(expression) Runtime-checked conversion of pointers and references within a single class hierarchy. Used for downcasting from a superclass to a subclass reinterpret_cast<Type>(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 Joey Paquet, 2007 -2014

Advanced Program Design with C++ 27 Data types: upcasting and downcasting • When dealing

Advanced Program Design with C++ 27 Data types: upcasting and downcasting • When dealing with classes and subclasses, one can declare objects of a supertype and manipulate them as one of its subclasses void display. Geometric. Object(Geometric. Object& g) { cout << "The radius is " << g. get. Radius() << endl; cout << "The diameter is " << g. get. Diameter() << endl; cout << "The width is " << g. get. Width() << endl; cout << "The height is " << g. get. Height() << endl; cout << "The area is " << g. get. Area() << endl; cout << "The perimeter is " << g. get. Perimeter() << endl; } Geometric. Object -----------area perimeter Circle ------radius diameter Rectangle ------width height • Problem: subclass members are undefined in superclass Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 28 Data types: upcasting and downcasting • May want

Advanced Program Design with C++ 28 Data types: upcasting and downcasting • May want to use static_cast: void display. Geometric. Object(Geometric. Object& g) { Geometric. Object* p = &g; cout << "The radius is " << static_cast<Circle*>(p)->get. Radius() << endl; cout << "The diameter is " << static_cast<Circle*>(p)->get. Diameter() << endl; cout << "The width is " << static_cast<Rectangle*>(p)->get. Width() << endl; cout << "The height is " << static_cast<Rectangle*>(p)->get. Height() << endl; cout << "The area is " << g. get. Area() << endl; cout << "The perimeter is " << g. get. Perimeter() << endl; } • 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. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

Advanced Program Design with C++ 29 Data types: upcasting and downcasting • Use dynamic_cast

Advanced Program Design with C++ 29 Data types: upcasting and downcasting • 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 Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2014

COMP 345 - Advanced Program Design with C++ 30 References • Y. Daniel Liang,

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