Chapter 12
Extending Your Classes
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 Edition 2
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
A First Book of C++ 4th Edition 3
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 Edition 4
Class Inheritance (cont'd.)
A First Book of C++ 4th Edition 5
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
A First Book of C++ 4th Edition 6
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
A First Book of C++ 4th Edition 7
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
A First Book of C++ 4th Edition 8
Access Specifications (cont'd.)
A First Book of C++ 4th Edition 9
Access Specifications (cont'd.)
• Example: Derive Cylinder class from Circle class
// BASE class declaration class Circle
{ protected: double radius; public:
Circle(double = 1.0); double calcval();
};
// class implementation
// constructor
Circle::Circle(double r)
{ radius = r;
}
// calculate the area of a circle double Circle::calcval()
{ return(PI * radius * radius);
}
// constructor
// constructor
A First Book of C++ 4th Edition 10
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
}
A First Book of C++ 4th Edition 11
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 Edition 12
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 Edition 13
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 Edition 14
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 Edition 15
Pointers as Class Members
• Class declaration for Program 12.6: list of book titles
– Titles accessed as illustrated in Figure 12.7
#include <iostream>
#include <string> 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
};
A First Book of C++ 4th Edition 16
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;
}
A First Book of C++ 4th Edition 17
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;
}
A First Book of C++ 4th Edition 18
Pointers as Class Members (cont'd.)
A First Book of C++ 4th Edition 19
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
A First Book of C++ 4th Edition 20
Assignment Operators and Copy
Constructors Reconsidered (cont'd.)
A First Book of C++ 4th Edition 21
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)
A First Book of C++ 4th Edition 22
Assignment Operators and Copy
Constructors Reconsidered (cont'd.)
A First Book of C++ 4th Edition 23
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
A First Book of C++ 4th Edition 24
Assignment Operators and Copy
Constructors Reconsidered (cont'd.)
A First Book of C++ 4th Edition 25
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
A First Book of C++ 4th Edition 26
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
A First Book of C++ 4th Edition 27
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
A First Book of C++ 4th Edition 28
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
A First Book of C++ 4th Edition 29
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
A First Book of C++ 4th Edition 30
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
A First Book of C++ 4th Edition 31
Class and Object Diagrams (cont’d.)
A First Book of C++ 4th Edition 32