Lecture 7-Week7 - Single Public and Private Inheritance-Constructor Chaining
Lecture 7-Week7 - Single Public and Private Inheritance-Constructor Chaining
(CS1143)
Week 7
2
Inheritance
3
4
Base Class and Derived Class
In C++, the most general class is called the base class (or super class)
and a more specific class is called the derived class (or subclass).
The derived class inherits all of the data members and member
functions of the base class (with the exception of constructors and
destructors), and it can create new data members and member
functions.
5
Private, Public and Protected Inheritance
6
Public Inheritance
7
Example
8
Example
9
Person Class
10
Student Class
11
main
12
Output
13
Description
On line 54, an object of the student class calls the member function
of its base class (Person) as if it were its own function
14
Private Members in Public Inheritance
15
Public and Protected Members in Public
Inheritance
A public member in the base class becomes a public member in the
derived class.
16
17
Week3. Slide 6.
18
Three Types of Inheritance
19
Outline
20
Constructors and Destructors
Unlike data fields and functions, the constructors and the destructor
of a base class are not inherited in the derived class.
The constructors and the destructor are not inherited because an
object of a derived class naturally has more data members than a
corresponding base class.
The constructor of a derived class must construct more; the destructor of a
derived class must destruct more.
21
Calling Base Class’s Constructors
You can invoke the base class’s constructor from the constructor
initializer list of the derived class.
22
Constructor Chaining
23
Destructor Chaining
24
Example
Calling base class constructor implicitly
25
26
27
28
Example
Calling base class constructor explicitly
29
30
31
32