CPSC 122 – Computer Science II
Gonzaga University – Department of Computer Science
Classes Cont.
Inheritance
allows a new class to be based on an existing class.
new class inherits all the member variables and functions of the class it is based on
except the constructors and destructor
Real world you can find many objects that are specialized versions of other more general
objects.
Inheritance
Inheritance
When an “is a” relationship exists between classes, it means that the
specialized class has all of the characteristics of the general class,
plus additional characteristics that make it special.
The base class is the general class (parent)
The derived class is the specialized class. (child)
class derivedClass : public baseClass
Accessibility
Derived class can access all public members of the base
class
Derived class cannot directly access any private
members from the base class
They can be accessed by the member functions of the base
class
Protected Members
Protected members of a base class are like private
members, but they may be accessed by derived classes.
Base Class Access
class derivedClass : public baseClass
Check point
What is the difference between private members and protected members?
Constructors and Destructors
The base class’s constructor is called before the derived
class’s constructor.
The destructors are called in reverse order, with the
derived class’s destructor being called first.
Rectangle – Cube Example
Calling Base Constructors through Derived
Class
Check point!
Redefining Base Class Functions
A base class member function may be redefined in a derived class.
Graded Activity Class Curved Activity Class
Class Hierarchy