1 / 36

DCO10105 Object-Oriented Programming and Design

DCO10105 Object-Oriented Programming and Design. Lecture 8: Polymorphism & C++ pointer Inheritance and polymorphism Pointer, dynamic memory, and pointer’s effect on class construction Dynamic binding and virtual function -- By Rossella Lau. Inheritance.

ion
Download Presentation

DCO10105 Object-Oriented Programming and Design

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. DCO10105 Object-Oriented Programming and Design • Lecture 8: Polymorphism & C++ pointer • Inheritance and polymorphism • Pointer, dynamic memory, and pointer’s effect on class construction • Dynamic binding and virtual function -- By Rossella Lau

  2. Inheritance A sub class has all the properties of its base class • Data members and function members, no matter if it is private, protected, or public • The type of the base class A sub class can play as its parent class when passing as a parameter; e.g., in scopePlayer.cpp, • Donald boxD(dewey); • deduct7(dewey); A sub class has many types – poly – morph (mask)

  3. Polymorphism • Polymorphism – many types • Same classes can play as different types (of ancestors) • Same expressions can perform different operations

  4. Same class acts as its ancestors • Same family members can be stored in the same container • Donald donalds[SIZE]; …… donalds[i] = dewey; • Vector<Donald> donalds(SIZE); …… donald[i] = dewey; • One function can be called with the same family members • deduct7(Donald &) in scopePlayer.cpp

  5. Same expression but different operations • When family members stored in the same container, e.g., donalds[i].print() invokes • Dewey::print() if donalds[i] stores dewey • Huey::print() if donalds[i] stores huey • Donald::print() if donads[i] stores donald

  6. bindingPlayer1.cpp • A parent’s function can also be identified through the instance of the child class by using BaseClass:: e.g. dewey.Donald::withdraw(10); • How about : (static_cast<Donald> (dewey)).withdraw (10); • It does not work! It does not have any effect even though dewey pretends to be a Donald!

  7. Static binding does not always work • The type cast of the above case is just a compiler binding, static binding, and dewey’s actual data type is still Dewey and it can’t really pretend to be a Donald during execution • In C++, to achieve actual execution type cast, dynamic binding, one should use pointer and define function to be overridden as virtual function

  8. 5000 …... …... 2004 2000 …... 0 Data and memory • All data required in a program must be in the memory • Memory is addressed from zero to, e.g., 512M-1 • Data in a location is referenced by an address • Data declared in a program will be assigned some memory spaces and referenced by the beginning of the address Memory in vertical view

  9. x's address is, for example, 2000 with the value of 0, and y is at 2004. …... …... y 2004 x 0 2000 …... 0 Simple data referencing in memory …… {int a, b; …… …… }

  10. Memory allocation for simple data • It depends on both the hardware and the compiler • Usually, for the C or C++ programs, the compiler/ system assigns a truck of memory for allocating: • Static space • Data survival while the program is running • Syntax: e.g., static int a;and global variables • Automatic space (or called a stack) • Data are alive only when data’s corresponding scope is running • Syntax: e.g., int a;

  11. p 2000 …... …... y 2004 x 0 2000 …... 0 Pointer A pointer stores the value of an address • In data declaration, e.g., int *p; • p is a pointer; • the content in the address of p is integer type, i.e., address 2000 stores an integer • In program executable statement, • the identifier, p, refers to an address (i.e., 2000) or it will be assigned an address • the identifier with an *(dereferencing), *p, refers to the data/object in the address of p • &id means the address ofid

  12. Pointer definition & expression • To declare a pointer e.g,. int * ptr; • To assign the address of a datum to a pointer, e.g., int a, b;ptr = &a; • To refer to the datum pointed to by a pointer (dereferencing) e.g., *ptr = 2; // same as a = 2b = *ptr; // same as b = a

  13. p p 2000 …... …... …... …... y y 2004 2004 x x 0 0 2000 2000 …... …... 0 0 Pointer - a conceptual sense

  14. Pointer Variables • The statement int *p; is equivalent to the statement int* p; which is equivalent to the statement int * p; • The character * can appear anywhere between the data type name and the variable name • int* p, q; Only p is the pointer variable, not q. Here q is an int variable (Malik’s slide: 14-5)

  15. Pointer Variables • To avoid confusion, we prefer to attach the character * to the variable name int *p, q; • The following statement declares both p and q to be pointer variables of the type int int *p, *q; (Malik’s slide: 14-6)

  16. The Address of Operator (&) • The ampersand, &, • is called the address of operator • is a unary operator that returns the address of its operand (Malik’s slide: 14-7) Note that & here is the “address of” operator, not the symbol for “reference”

  17. The Dereferencing Operator (*) • C++ also uses * as a unary operator • When used as a unary operator, *, • commonly referred to as the dereferencing operator or indirection operator, • refers to the object to which its operand (that is, a pointer) points (Malik’s slide: 14-8)

  18. Dynamic Variables • Variables that are created during program execution are called dynamic variables • With the help of pointers, C++ creates dynamic variables • new and delete, to create and destroy dynamic variables, respectively • When a program requires a new variable, the operator new is used • When a program no longer needs a dynamic variable, the operator delete is used • In C++, new and delete are reserved words (Malik’s slide: 14-9)

  19. Exercises • Malik Exercise: 14:3-4 • What is the output of the following C++ code? int x; int y; int *p = &x; int *q = &y; *p = 35; *q = 98; *p = *q; cout << x << “ “ << y << endl; cout << *p << “ “ << *q << endl; int x; int y; int *p = &x; int *q = &y; x = 35; y = 46; p = q; *p = 78; cout << x << “ “ << y << endl; cout << *p << “ “ << *q << endl;

  20. Array and pointer • In C, an array id is also a pointer • For static array, it is a constant pointer • For dynamic array, it can be used as a normal pointer • The array id, array, refers to the starting address of the array; i.e., array refers to the address of array[0] • E.g., int *array; or int array[SIZE]; • array is the starting address of the array • array is also the address of array[0] • *array is the same as array[0] • If it is a dynamic array (the first form), it allows forint *ptr; ptr = arrary; array = ptr; • However, if it is a static array (the second form), array is a constant pointer, it does not allow for array = ptr;

  21. Null pointer A pointer can have null value, e.g., ptr = 0; • This pointer with a value of binary zero is also called a null pointer • It represents that the pointer refers to nothing • Checking: • if (ptr) // to check if a pointer refers to something • if (!ptr) // to check if a pointer is null • if (ptr == NULL) // C style to check for a null pointer

  22. Calling function copying Called function Parameter passed by pointer (for efficiency) • When an object is passed to a function, copying of the object is not efficient • Passed by a pointer, equivalent to passed by a reference, is more efficient: only the value of the pointer is copied E.g., functions in array.cpp of Lecture 4

  23. Constant pointers/reference • Objects passed by pointers may be modified since the object is pointed to by the called function • On many occasions, objects are only for reference purposes; e.g., parameters of many operators such as +, -, *, /, cout. • C++ provides a keyword const to specify that an object (including pointers) can be a constant and/or the object referenced can be a constant; i.e., the object referenced remains unchanged; e.g.,: • int const *cip; // pointer to an int const • int *const icp; // pointer const to an int • int const *const cicp; // pointer const to an int const

  24. Danger pointers • Dangling pointer: a pointer points to an object which is not available or overwritten by others • Invalid address reference; e.g., use of null pointers. …… a_ptr = a_fun() …… int *a_fun() { int a; …… return &_a; // space of a // released // before a_fun // ends }

  25. Pointer and memory allocation //Misuse of null pointer int *p; *p = 1320; // illegal!! • The declaration of a pointer does not provide any memory space for its target • Dynamic space can be obtained by the operator new • Dewey *p = new Dewey; // get space for an instance • Dynamic space is in an area managed by the operating system and is permanent – it allows the object to be created and then used in different functions • C-style gets dynamic space by using malloc()

  26. Memory allocation for dynamic array • The following will cause the system to fail when length is a variable, int array[length]; • To obtain space for an array: int *array = new int[length]; • Remember to avoid misuse of null pointers: int *array; cout << *array; // array does not refer // to any real block!

  27. Dynamic memory de-allocation • Unlike Java, C does not automatically resume dynamic spaces • If one continues to do allocation, the system will crash because of running out of memory – it is also called memory leak. • It is required to de-allocate the occupied space before the program is terminated delete dewey; delete[] array; //must use this form for array • C-style: delete()

  28. Notes to memory de-allocation • Local variables defined in each function will be automatically released just before a function is terminated • Instances declared as an ordinary variable, not a pointer, e.g., Donald donald;will also be released in the same way • Global variables are automatically released just before a program is terminated • However, dynamic space assigned by using new will not be released as in the above manner.

  29. Pointer and class • A member function in OOP must be invoked with an instance object; e.g., dewey.print(); • The instance object is the associated object of each member function defined in a class • In Java, the associated object is “this”, a reference • In C++, “this” is a pointer • To refer to the associated object, use *this • To identify a member, e.g., use thisa = a; in Quadratic.cpp

  30. Pointer as a data member • When there is a pointer data member, most likely, it will point to dynamic memory; • e.g., class IntArray stores a dynamic array, a pointer • Care should be taken during class construction since the following can be automatically generated by the compiler: • Default constructor & Destructor • Copy constructor & Assignment operator • Care should be taken to be sure whether a shallow copy or a deep copy is needed (Malik’s slide: 14: 16, 21) • Class IntArray, similar to classes in the STL, performs deep copy

  31. Shallow Copy vs Deep Copy • In a shallow copy, two or more pointers of the same type point to the same memory; that is, they point to the same data • In a deep copy, two or more pointers have their own data (Malik’s slide: 14-16)

  32. The Assignment Operator (Malik’s slide: 14-16)

  33. Using pointer for dynamic binding • bindingPlayer2.cpp • (static_cast<Donald> (dewey))->withdraw (10); takes effect! • Sub classes should be able to pretend to be the base class and then plays its own role again such as the call playPrint(); on line 32 • But the execution shows that for donald->print()of playPrint(), it uses only the print() of the base class

  34. Dynamic binding • To simplify defining many functions for playPrint(), the print() of the base class can be defined as a virtual function in order to allow one expression to perform different operations • E.g., DonaldFamilyVirtual.h & bindingPlayer3.cpp • Change void print() const; to virtual void print() const; • The execution inside playPrint() can perform different print() according to the actual data type of the passed object! • Dynamic binding in C++ should be achieved by both pointers and virtual functions

  35. Summary • Polymorphism means an object can play different roles through static binding or dynamic binding • Dynamic binding in C++ must be achieved by pointers and virtual functions • A pointer stores an address and can apply de-referencing and object member identification • Pointer is a powerful but also a dangerous feature and thus in C++, reference is used more • When there is a pointer data member, care must be taken in defining default constructor, copy constructor, assignment operator, and destructor

  36. Reference • Malik: 14 -- END --

More Related