1 / 48

C++ Programming

C++ Programming. Jerry Lebowitz. Chapter 12. Topics. Pointers Dynamic memory Object persistence Shallow vs. deep copy Array of pointers Command line parameters Virtual Functions. What is a Pointer Variable?.

shaun
Download Presentation

C++ Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Programming Jerry Lebowitz

  2. Chapter 12

  3. Topics • Pointers • Dynamic memory • Object persistence • Shallow vs. deep copy • Array of pointers • Command line parameters • Virtual Functions

  4. What is a Pointer Variable? • A pointer variable is a variable whose value is the address of a location in memory • To declare a pointer variable, one must specify the type of value that the pointer will “point to” • For example: int * intPointer// intPointer can hold the address of an int char * charPointer; // charPointer can hold the address of a char • (See example: pointer1.cpp)

  5. Dereferencing a Pointer Variable • The unary indirection (dereference) operator * is used to determine the value of the variable pointed to by a pointer variable • The value can be accessed or changed by using the dereferencing operator value address myInt 7 1000 myIntPtr 1000 4000 One can access the memory location using myInt or *myIntPtr • (See example: pointer2.cpp)

  6. Classes, Structs, and Pointer Variables • One can declare pointers to other data types, such as classes and structs struct studentType { char name[26]; double gpa; int ssn; char grade; }; studentType student; studentType* studentPtr; studentPtr = &student;

  7. Accessing Members • Three different ways to store 3.9 in the component gpa of the object student • student.gpa = 3.9; • (*studentPtr).gpa = 3.9; • studentPtr->gpa = 3.9; • Since dot has a higher precedence than the dereferencing operator, parentheses are important • C++ provides an operator, called the member access operator arrow, ->. • The syntax for accessing a class (struct) member using the operator -> is pointerVariableName->classMemberName

  8. Operations using Pointer Variables • Assignment • Value of one pointer variable can be assigned to another pointer variable of the same type • Relational operations • Two pointer variables of the same type can be compared for equality, etc. • Some limited arithmetic operations • Integer values can be added and subtracted from a pointer variable • Value of one pointer variable can be subtracted from another pointer variable

  9. Pointer Arithmetic • Why is there a different pointer type for each type? • C++ does pointer arithmetic • To point to the variable, C++ must add a value the equal to the sizeof the type of the variable • charPtr + 1 is +1 (sizeof of char) • if charPtr contains the address 2400 then charPtr+1 contains 2401 • intPtr +1 is +4 (sizeof of int) • if intPtr contains the address 2400 then intPtr+1 contains 2404 • floatPtr+1 is +4 (sizeof of float) • if floatPtr contains the address 2400 then floatPtr+1 contains 2404 • (See examples: pointer3.cpp through pointer7.cpp)

  10. Differences between Arrays and Pointers • The name of an array evaluates to the address in memory of the first element in the array • It cannot be changed • It is called a pointer constant (Arrays are fixed in memory) • It cannot be used on the left-hand side of an assignment and intArray++ is illegal • Pointer variables can be changed • They can appear on either side on either side of an assignment statement • Assignments are allowed between array address and pointers

  11. Arrays as Parameters to Functions • It is not possible to pass a copy of the array • The address of the array name serves as the parameter and the function can access the array elements through the address • Prototypes and function definitions • One can use pointer or array notation (In reality, array notation is same as dereferencing a variable) • Inside the function, the function can access the elements using array or pointer notation regarding of the type used on the function definition or prototype • Functions have no knowledge of the number of elements (just the type) • (See examples: pointer8.cpp and pointer9.cpp)

  12. Differences Between Reference and Pointer Variables • * (dereference) and & (address of) operators are not used with reference variables • The compiler automatically dereferences reference variables • Reference variables must be initialized while pointer variables may or may not • The compiler treats a reference variable as if it is a constant pointer • cannot be reassigned after being initialized • (See examples: pointer10.cpp and pointer11.cpp)

  13. Pointers within Classes • See example: pointer12.cpp

  14. Types of C++ Variables • Static variables • Once defined, memory allocation exists throughout execution of program (initialized to zero upon creation) • static int myInt; • Automatic variables • Automatically created at function entry and is destroyed when returned from function • int myInt; or auto int myInt; • Static and automatic memory space allocation is done compile time • Dynamic variables • Explicitly allocated and deallocated during program execution • Efficient use of memory

  15. Allocation of Memory STATIC ALLOCATION Static allocation is the allocation of memory space at compile time DYNAMIC ALLOCATION Dynamic allocation is the allocation of memory space at run time by using operator new

  16. Operator new Syntax Syntax: new DataType or new DataType [IntExpression] • If memory is available in an area called the heap (or free store) the new operator allocates the requested object or array, and returns a pointerto (address of ) the memory allocated • Program terminates with error message if space in not available • The allocated memory is uninitialized • The dynamically allocated object exists until the delete operator destroys it (See example: dynamic1.cpp) 16

  17. Using Operator delete • The “delete”operator returns to the free store (heap) memory which was previously allocated at run-time by “new” operator • The object or array currently pointed to by the pointer is deallocated • Pointer is considered unassigned 17

  18. Operator delete Syntax Syntax: delete Pointer or delete [ ] Pointer • The object or array currently pointed to by Pointer is deallocated • Value of the Pointer is undefined • The memory is returned to the free store (heap) • Square brackets are used with delete to deallocate a dynamically allocated array • (See example: dynamic2.cpp) 18

  19. Inaccessible Object • An inaccessible object is an unnamed object that was created by operator new and which a programmer has left without a pointer to it • A memory leak is the loss of available memory space that occurs when dynamic data is allocated but never deallocated

  20. Making an Object Inaccessible ptr ptr2 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; // here the 8 becomes inaccessible (see example: dynamic3.cpp) 8 -5 ptr ptr2 8 -5

  21. A Dangling Pointer • Is a pointer that points to dynamic memory that has been deallocated int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; delete ptr2; // ptr is left dangling ptr ptr2 8 -5

  22. Object Persistence • All objects have a life cycle • Object are created • Object exist and are accessible • Objects are terminated (destroyed) • Object persistence characterizes the different object creation and termination mechanisms

  23. Types of Persistence • Automatic • Objects are created at an arbitrary point (usually in a block) and are automatically terminated at the end of scope • Static • Once objects are created they are in memory until the final explicit instruction of the program • Dynamic • Objects are created at an arbitrary point and are terminated under programmer control • Type of persistence should be chosen for a particular object depending on context

  24. Automatic Persistence • Usually declared in a block • Default mechanism in C++ • Usually exists for a short lifetime • Exists on the run time stack (stack grows and shrinks as objects come and go) • (see example: dynamic4.cpp)

  25. Static Persistence • Once defined, objects exist throughout the program • Global implies static • (see example: dynamic5.cpp)

  26. Dynamic Persistence • Objects put on the heap using the “new” operator • Objects removed from the stack using “delete” operator • (see examples: dynamic6.cpp and dynamic7.cpp)

  27. Shallow Copy vs. Deep Copy • A shallow copy copies only the class data members • Does not make a copy of any pointed to data • Shares any pointed-to dynamic data with the original class object • A deep copy copies not only the class data members • Makes a separate stored copy of any pointed-to data • Makes its own copy of the pointed-to dynamic data at different locations than the original class object

  28. 7 7 4 4 2014 2014 message message Problems doing a Shallow Copy Fourth of July Two objects pointing to the same memory location 1. Changing string affects both objects 2. Deleting string affects both objects

  29. 7 7 4 4 2014 2014 Fourth of July Fourth of July message message Deep Copy Two objects pointing to the different memory locations 1. Changing a string affects only one object 2. Deleting a string affects only one object

  30. Initialization of Class Objects • Initialization means • Initialization in a variable declaration • object object1=object2; // not the assignment operator • Passing an object argument by value (copy) • myFunction(object1) • Returning an object as the return value of a function (not by reference) • return (object1) • By default, C++ uses shallow copies for these initializations

  31. Classes using Dynamic Memory • When dealing with classes that use dynamic memory (common with pointers), one must define • Class constructor (other than the default) • Class destructor • When a class variable (that uses dynamic memory) goes out of scope, the memory for data members including pointers is deallocated • Should deallocate the dynamic memory pointed to by the data member • Dynamic memory to is not automatically deallocated • Copy constructor • (Optionally) a deep copy function or method • (Optionally) an assignment operator that performs a deep copy

  32. 7 4 2014 Fourth of July message Destructor Issues Default destructor does not delete the pointed to data

  33. Copy Constructor • When present (default shallow copy is not done), it is implicitly called in initialization situations • Should be written to make a deep copy of the dynamic data into different memory locations • Syntax: className (const className& objectName); // copy constructor • Like other constructors, it has no return type • Clients CANNOT invoke the copy constructor directly • A deep copy function may also be written • See examples: dynamic8.cpp and dynamic9.cpp

  34. pointers strings These are to Arrays of Pointers • char * ptrArray[4] is a char and since [ ] has a higher precedence than * ptrArray is array of four character pointers See examples: apointers1.cpp through apointers3.cpp)

  35. Command Line Parameters • Passing information from O/S to C++ • Declare arguments to main() • int main( int argc, char *argv[ ] ) // array of character pointers • int main( int argc, char **argv ) // array of character pointers • argc is the number of parameters (program name is the first) • argv[ ] contains the addresses of the command line parameters (is an array of character pointers that point to the actual arguments) • (See example: command1.cpp)

  36. Static Vs Dynamic Binding • Static Binding • Is the compile-time determination of which function to call for a particular object based on the type of the formal parameter • Dynamic Binding • Is the run-time determination of which function to call for a particular object

  37. Static Binding Is Based on Formal Parameter Type • For example: …. Time startTime(6,30,0) ; ExtTime endTime(5,0,0,PST) ; …. startTime.write() endTime.write() …. startTime.write() // invoke the Write() function from the Time class endTime.write() // invoke the Write() function from the ExtTime class • The determination to invoke the proper Write() function is done at compile time • Static Binding

  38. Passing Class Objects as Arguments • The basic rule for passing class objects as arguments is that the actual argument and the corresponding formal parameter must be the same type • The parameters on the invocation must be the same type as defined on the function • This rule is relaxed when dealing with inheritance • When the type of a formal parameter is a parent class, the argument used can be: • The same type as the formal parameter (parent class) or any descendant class type • Compilers use a set of rules to determine the binding of an function when an class object is passed as an argument

  39. Passing Class as Arguments(continued) • One can pass an object of a child class to a function that expects an object of a parent class but not visa versa • A single function can handle parent class objects and all descendant class objects • Instead of writing a different function for each type of object • For example, a single print function can handle the Time objects as well as all of the Time’s descendant objects

  40. Slicing Problem • When an object of a child class is passed to a function that expects an object of its parent class using passing by value • Only the data members in common are passed • Static binding occurs • The child usually contains more data members • The extra data members are “sliced off” • This slicing also occurs using the assignment operator • parentClassObject = childClassObject

  41. Slicing Problem Illustrated … Time startTime (8,45,0); ExtTime thisTime ( 8, 35, 0, PST ) ; ... Print(startTime); Print(thisTime); …. void Print (Time someTime) // pass by value { someTime.Write(); } Time is 08:45:00 Time is 08:35:00 • Note: timezone is not printed • (See example virtual1.cpp)

  42. Avoiding the Slicing Problem • When passing by reference, the slicing problem does not occur since the address of the argument is sent to the function and no copy is done • However static binding still occurs • Compilers will generate code to call the base class’s function • Adding the word virtual at the beginning of the function declaration (prototype) • Instructs the compiler to generate code that dynamically binds a function to an object

  43. Time Specification - virtual Write( ) class Time { public : void Set ( int hours , int minutes , int seconds ) ; void Increment ( ) ; virtual void Write ( ) const ; Time ( int initHrs, int initMins, int initSecs ) ; Time ( ) ; private : int hrs ; int mins ; int secs ; } ;

  44. Slicing Problem Solved … Time startTime (8,45,0); ExtTime thisTime ( 8, 35, 0, PST ) ; ... Print(startTime); Print(thisTime); …. void Print (Time& someTime) // pass by reference { someTime.Write(); } Time is 08:45:00 Time is 08:35:00 PST • (See example: virtual2.cpp)

  45. Dynamic Binding Summary • Declaring a member function to be virtual • Instructs the compiler to generate code that performs dynamic binding • Determination of what function to call is done at run time • Dynamic binding requires pass-by-reference when passing a class object to a function • In the declaration for a virtual function, the word virtual appears only in the base class • A derived class is not required to re-implement a “virtual” function • If it does not, the base class version is used • A derived class cannot redefine the function return type of a virtual function

  46. Classes and Virtual Destructors • If a derived class object is passed to a formal parameter of the base class type, the destructor of the base class is called when the derived class object goes out of scope • If the derived class contains pointer variables • The derived class destructor should be called to de-allocate memory • If the destructor of the base class is virtual, this will occur • If the base class contains virtual methods, then one should make the destructor virtual

  47. Abstract Classes and Pure Virtual Functions (1) • The base class can contain functions that you would want each derived class to implement • The base class may contain functions that may not have meaningful definitions in the base class • For example, for the class Shape • The draw () and move () make sense only if the shape is defined (square, rectangle, circle, etc.) • virtual void draw () • virtual void move (double x, double y)

  48. Abstract Classes and Pure Virtual Functions (2) • To prevent someone from invoking draw () and move () for a class shape object, use the following • virtual void draw () = 0; • virtual void move (double x, double y) = 0; • This construct will create pure virtual functions • A class that contains a pure virtual function is call an abstract class • One cannot instantiate abstract classes since all the methods are not implemented • The derived class must implement the pure virtual functions (see example 12-9) • Note: a constructor cannot be virtual

More Related