1
COEN 244 – PROGRAMMING METHODOLOGY II
Topic 04
Inheritance
2
Class Inheritance
• Inheritance is a mechanism that allows the
derivation of new classes from existing ones
• Class derivation is where new classes (called
derived classes) are created based on existing
classes (called base classes)
• Derived classes inherit all members of the base
class
3
Class Inheritance (cont.)
• The inherited class may add, overload, or
override functionality
• Inheritance promotes reuse by reusing the base
class and also promotes a better maintainability
and extensibility of the system
• Inheriting from derived classes is also possible,
creating inheritance hierarchies
4
Example
Person
Student Professor
GraduateStudent UndergraduateStudent FullTimeProfessor PartTimeProfessor
5
Example (cont.)
• The classes Student and Professor inherit all attributes
of the class Person
– They can also define their own attributes
• Classes GraduateStudent and UndergraduateStudent
inherit all attributes of Person and Student
– Same applies to FullTimeProfessor and
PartTimeProfessor
6
Inheritance in C++
• To specify that a class inherits from another class in
C++, you need to use the following syntax
class <base_class> {
...
};
class <derived_class> : <access_specifier> <base_class> {
...
};
• Access specifier: public, private, or protected
• For now, we use public only
7
Base Class: Student
• Assume we have the following Student class
class Student { // base class
public:
Student(int, string, string); // constructor
...
private:
string fname;
string lname;
int id;
};
• Assume: later we need to implement a
UndergradStudent class
8
Derived Class: UndergradStudent
class UndergradStudent : public Student { // derived class
public:
UndergradStudent (int, string, string); //Constructor
void setGrade( float, float, float );
private:
float assignment;
float midterm;
float final;
};
• Note:
– The attributes fname, lname and id are inherited from
the class Student
– Each class has its own constructor
9
Initializing base class members
using a member initialization list
• It is recommended to initialize data members of a
base class using a member initialization list
• Example
class UndergradStudent : public Student // derived class
{
public:
UndergradStudent (int, string, string); //Constructor
void setGrade( float, float, float );
private:
float assignment;
float midterm;
float final;
};
10
UndergradStudent (int id1, string fname1, string lname1): Student(id1,
fname1, lname1) {
assignment = 0.0;
midterm = 0.0;
final = 0.0;
}
• The constructor of UndergradStudent calls the constructor of Student
with a member initializer and after that initializes assignment, midterm,
and final
• Let’s see the full program, which is on Moodle.
11
Access modifier: Protected
• The protected member access specifier gives
intermediate access
• A protected member can be accessed
– by members of its class and
– the derived classes of the class that defines it
• To define a member as protected, use the keyword
protected
• Example is on Moodle.
12
The is-a rule
• Inheritance must satisfy the is-a rule
– A derived class is a special case of the base class
• Examples:
– A student is a person
– A professor is a person
– An undergraduate student is a student, which is a person
– A rectangle is a shape
– A car is a vehicle
13
Constructors and destructors in
inheritance
• When an object of a derived class is created the base
constructor is called first, then the derived class
constructor
• When that object is destroyed the destructors are
called in the reverse order
– The destructor of the derived class is called first and then the
destructor of the base class
• The constructors and destructors are not inherited
14
Note about derived class objects
• A derived class object can be assigned to any of its public base
class objects:
class Base {
...
private:
int x,y;
};
class Derived : public Base
{
...
private:
int z;
};
Base b; // x and y are set
Derived d; // x, y, and z are set
b = d; // fill the fields of b with the corresponding values in d
15
The order of construction
• To create a derived class object:
1. The base part is first allocated,
2. The base class constructor is called,
3. The derived part is allocated,
4. The derived class constructor body is executed
• The above procedure is implemented
recursively in a hierarchy
16
What about the destructors?
• When a derived class object is being
destroyed:
– The derived destructor is executed first;
– The base destructor is called
• Always make sure that your destructors are
well defined
17
Types of Inheritance
• There exist three types of access specifiers
with inheritance:
– public: class Derived : public Base { ... };
– protected: class Derived : protected Base { ... };
– private: class Derived : private Base { ... };
• They determine different access levels of
data members of a base class from derived
classes
18
Types of Inheritance (cont.)
• Public inheritance:
– The public members of the base class become public
members of the derived class
– The protected members of the base class become
protected members of the derived class
– The private members stay private
– This type is the most used one
• Protected inheritance:
– The public and protected members of the base class
become protected members of the derived class
– The private members stay private
19
Types of Inheritance (cont.)
• Private inheritance:
– The public and protected members of the base class
become private members of the derived class
– Private members of the base class stay private
20
Function Overriding
• The derived class can redefine the inherited member
functions
– This is known as function overriding
• Do not confuse this with function overloading
– Which can be applied whether there is inheritance or not
• Function overriding is a good way to make a base class
member function specific to the derived class that
overrides it
21
How does it work?
• The derived class redefines a member function
with the same signature (number and type of
parameters) as the base class member function to
override
• Member function overriding is used only with
inheritance
• The scope resolution operator (::) may be used in
the derived class to access the base class
overridden member function
22
Example
class Employee {
public:
Employee(string, string);
void print() const;
protected:
string fname;
string lname;
};
Employee::Employee( string fname1, string lname1) {
fname = fname1
lname = lname1;
}
23
void Employee::print() const {
cout << fname << “ ” << lname << endl;
}
24
class HourlyWorker : public Employee {
public:
HourlyWorker(string, string, double, double);
double getPay() const;
void print() const;
private:
double wage;
double hours;
};
// constructor
HourlyWorker::HourlyWorker(string pf, string pl, double w, double h)
: Employee( pf, pl ) {
wage = w;
hours = h;
}
double HourlyWorker::getPay() const {
return wage*hours;
}
25
// Overridden print function
void HourlyWorker::print() const {
Employee::print(); // Print Employee name
cout << ":" << getPay() << endl;
Example of using Employee and HourlyEmployee
Employee e1(‘‘John’’, ‘‘Young’’);
e1.print(); // print() of class Employee is called
HourlyWorker h1(‘‘Frank’’, ‘‘User’’, 150, 500);
h1.print(); // print() of HourlyWorker is called
26
Multiple inheritance
• Single inheritance: one base class as a parent
class in the inheritance hierarchy
• Multiple inheritance: a derived class has more
than one base class )
– There is no limit on the number of base classes in multiple
inheritance
– Access rules and mode of derivations for multiple inheritance
are the same as for single inheritance
– A derived class inherits all data and method members of all
bases
27
Example of multiple inheritance
Professor
Student FullTimeProfessor PartTimeProfessor
UndergraduateStudent GraduateStudent
28
Problems with multiple inheritance
• Multiple inheritance is considered as a bad design
• Do not used it unless it is really necessary!
• Alternative to multiple inheritance:
– if you need to design a class that provides to its client
the union of services provided by other classes
– try first composition, then composition with inheritance,
and lastly multiple inheritance