Download presentation
Presentation is loading. Please wait.
Published byElaine O’Neal’ Modified over 8 years ago
1
A First Book of C++ Chapter 12 Extending Your Classes
2
Objectives In this chapter, you will learn about: –Class Inheritance –Polymorphism –Dynamic Object Creation and Deletion –Pointers as Class Members –Common Programming Errors –UML Class and Object Diagrams A First Book of C++ 4th Edition2
3
3 Class Inheritance Deriving one class from another class Polymorphism allows redefining how member functions of the same name operate Base class (parent class, or superclass): initial class used as basis for derived class Derived class (child class, or subclass): new class that incorporates all of the data and member functions of its base class –Usually adds new data and function members –Can override any base class function
4
Class Inheritance (cont'd.) Example of inheritance: three geometric shapes: circle, cylinder, and sphere –Shapes share common characteristic: radius –Can make circle base type for the other two shapes (Figure 12.1) –By convention, arrows always point from derived class to base class Reformulating these shapes as class types, we would make circle base class and derive cylinder and sphere classes from it A First Book of C++ 4th Edition4
5
5 Class Inheritance (cont'd.)
6
A First Book of C++ 4th Edition6 Class Inheritance (cont'd.) Simple inheritance –Each derived type has only one base type Multiple inheritance –Derived type has two or more base types Class hierarchies –Illustrate the hierarchy, or order, in which one class is derived from another
7
A First Book of C++ 4th Edition7 Access Specifications Until now, we have used only private and public access specifiers within class private status ensures that data members can be accessed only by class member functions or friends –Prevents access by any nonclass functions (except friends) –Also precludes access by any derived class functions
8
A First Book of C++ 4th Edition8 Access Specifications (cont'd.) protected access: third access specification permits only member or friend function access –Permits this restriction to be inherited by any derived class –Derived class defines its inheritance subject to base class’s access restrictions Class-access specifier: listed after colon at start of its declaration section, defines inheritance Table 12.1 lists inherited access restrictions
9
A First Book of C++ 4th Edition9 Access Specifications (cont'd.)
10
A First Book of C++ 4th Edition10 Access Specifications (cont'd.) Example: Derive Cylinder class from Circle class // BASE class declaration class Circle { protected: double radius; public: Circle(double = 1.0); // constructor double calcval(); }; // class implementation // constructor Circle::Circle(double r) // constructor { radius = r; } // calculate the area of a circle double Circle::calcval() { return(PI * radius * radius); }
11
A First Book of C++ 4th Edition11 Access Specifications (cont'd.) Example: Derived Cylinder class // class declaration section where // Cylinder is derived from Circle class Cylinder : public Circle { protected: double length; // add one additional data member and public: // two additional function members Cylinder(double r = 1.0, double l = 1.0) : Circle(r), length(l) {} double calcval(); }; // class implementation double Cylinder::calcval() // this calculates a volume { return (length * Circle::calcval()); // note the base // function call }
12
Polymorphism Permits same function name to invoke one response in objects of base class and another response in objects of derived class –Example of polymorphism: overriding of base member function using an overloaded derived member function, as illustrated by the calcval() function in Program 12.1 Function binding: determines whether base class or derived class version of function will be used A First Book of C++ 4th Edition12
13
Polymorphism (cont'd.) Static binding: determination of which function to be called is made at compile time –Used in normal function calls Dynamic binding: determination of which function to be called is made at runtime (via virtual function) Virtual function (Example in Program 12.2): creates pointer to function to be used –Value of pointer variable is not established until function is actually called –At runtime, and on the basis of the object making the call, the appropriate function address is used A First Book of C++ 4th Edition13
14
Dynamic Object Creation and Deletion Dynamic allocation: amount of storage to be allocated is assigned, as requested, at runtime –Instead of being fixed at compile time –Useful when dealing with lists and objects A First Book of C++ 4th Edition14
15
Dynamic Object Creation and Deletion (cont'd.) After an object has been dynamically created –It can be accessed only by using the address the new operator returns Example: Checkout *anotherTrans; anotherTrans = new Checkout; Deleting dynamically created objects when their usefulness ends is crucial Memory leak: after an existing object’s address is overwritten with a new object’s address, there’s no way for the system to reclaim the memory A First Book of C++ 4th Edition15
16
A First Book of C++ 4th Edition16 Pointers as Class Members Class declaration for Program 12.6: list of book titles –Titles accessed as illustrated in Figure 12.7 #include using namespace std; class Book { private: char *title; // a pointer to a book title public: Book(char * = '\0'); // constructor void showtitle(void); // display the title };
17
A First Book of C++ 4th Edition17 Pointers as Class Members (cont'd.) Implementation section for Program 12.6 –Defines Book() and showtitle() functions // class implementation section Book::Book(char *name) { title = new char[strlen(name)+1]; // allocate memory strcpy(title,name); // store the string } void Book::showtitle(void) { cout << title << endl; }
18
A First Book of C++ 4th Edition18 Pointers as Class Members (cont'd.) main() function of Program 12.6 int main() { Book book1("Windows Primer"); // create 1st title // 2nd title Book book2("A Brief History of Western Civilization"); book1.showtitle(); // display book1's title book2.showtitle(); // display book2's title return 0; }
19
A First Book of C++ 4th Edition19 Pointers as Class Members (cont'd.)
20
A First Book of C++ 4th Edition20 Assignment Operators and Copy Constructors Reconsidered If a class contains no pointer data members, compiler-supplied defaults work well for assignment operators and copy constructors –Compiler defaults provide member-by-member operation with no adverse side effects –Problems occur with defaults if pointers are involved Example of problem: –Figure 12.9a shows pointers and allocated memory of Program 12.6 before execution
21
A First Book of C++ 4th Edition21 Assignment Operators and Copy Constructors Reconsidered (cont'd.)
22
A First Book of C++ 4th Edition22 Assignment Operators and Copy Constructors Reconsidered (cont'd.) Example of problem (cont'd.): –Now insert statement: book 2 = book1; before closing brace of main() Compiler default assignment is used Produces memberwise copy –Address in book1 ’s pointer is copied into book2 ’s pointer –Both pointers now point to same address –Address of A Brief History of Western Civilization is lost (as shown in Figure 12.9b)
23
A First Book of C++ 4th Edition23 Assignment Operators and Copy Constructors Reconsidered (cont'd.)
24
A First Book of C++ 4th Edition24 Assignment Operators and Copy Constructors Reconsidered (cont'd.) Example of problem (cont'd.): –Effect of loss of address of: A Brief History of Western Civilization No way for operating system to release this memory (until program terminates) If destructor attempts to release memory pointed to by book2, book1 will point to an undefined memory location Solution to problem: copy book titles and leave pointers alone (as in Figure 12.9c) – Must write our own assignment operator
25
A First Book of C++ 4th Edition25 Assignment Operators and Copy Constructors Reconsidered (cont'd.)
26
A First Book of C++ 4th Edition26 Assignment Operators and Copy Constructors Reconsidered (cont'd.) Definition of assignment operator void Book::operator=(Book& oldbook) { if(oldbook.title != NULL) // check that it exists delete(title); // release existing memory title = new char[strlen(oldbook.title) + 1]; // allocate new memory strcpy(title, oldbook.title); // copy the title } Problems associated with assignment operator also exist with default copy constructor –Need to also define a new copy constructor
27
A First Book of C++ 4th Edition27 Common Programming Errors Attempting to override a virtual function without using the same type and number of arguments as the original function Using the keyword virtual in the class implementation section Forgetting to delete dynamically created objects Attempting to use memberwise assignment between objects containing a pointer member
28
A First Book of C++ 4th Edition28 Summary Inheritance is the capability of deriving one class from another class Base class functions can be overridden by derived class functions with the same name Polymorphism is the capability of having the same function name invoke different responses In static binding, the determination of which function is called is made at compile time A virtual function designates that dynamic binding should take place
29
A First Book of C++ 4th Edition29 Summary (cont'd.) Pointers can be included as class data members –Adhere to same rules as pointer variables Copy default constructors and default assignment operators are typically not useful with classes that contain pointer members
30
A First Book of C++ 4th Edition30 Chapter Supplement: UML Class and Object Diagrams Program modeling –Process of designing an application Unified Modeling Language (UML) –Widely accepted as a technique for developing object-oriented programs –Uses diagrams and techniques that are easy to understand Each item is addressed by separate views and diagrams UML has nine diagram types
31
A First Book of C++ 4th Edition31 Class and Object Diagrams Class diagrams –Used to describe classes and their relationships Object diagrams –Used to describe objects and their relationships Attributes have two qualities: type and visibility –Type is either a primitive data type or a class data type –Visibility defines where an attribute can be seen: private, public, protected
32
A First Book of C++ 4th Edition32 Class and Object Diagrams (cont’d.)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.