LECTURE 23
Inheritance Basics
Types of Inheritance
(Simple , Multi-Level , Multiple and Hierarchal
)
Definition
• This mechanism of deriving a new class from
existing/old class is called “inheritance”.
• The old class is known as “base” class,
“super” class or “parent” class”
• The new class is known as “sub” class
“derived” class, or “child”
class.
• Example:
MAMMALS
DOGS C A TS HUMANS
L IO N S TIG E R S LEO PARDS
Inheritance:
Introduction
Reusability--building new components by utilizing
existing components- is yet another important aspect of
OO paradigm.
It is always good/ “productive” if we are able to reuse
something that is already exists rather than creating the
same all over again.
This is achieve by creating new classes, reusing the
properties of existing classes.
It saves money , time etc.
To use a class that is already created and tested
properly saves the effort of testing and developing same
again.
Define a Class Hierarchy
• Syntax:
class DerivedClassName : access-level BaseClassName
where
– access-level specifies the type of derivation
• private by default, or
• public
• Any class can serve as a base class
– Thus a derived class can also be a base class
Implementing Inheritance in C++ by Deriving Classes
From the Base Class
• Syntax:
class <base_class>
{
…
};
class <derived_class> : <access-specifier>
<base_class>
{
...
};
What to inherit?
• In principle, every member of a base class is
inherited by a derived class
– just with different access permission
• However, there are exceptions for
– constructor and destructor
– operator=() member
– friends
Since all these functions are class-specific
Access specifiers of derivation
The public access specifier
The protected access specifier
The private access specifier
Sequence of invoking
constructors and destructors
Constructors are called in the order
of Base – to – Derived
Destructors are called in the order
of Derived – to – Base
FORMS OF INHERITANCE
• Single Inheritance
• Multi-level Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
Object-Oriented
10
Programming Using C++,
Third Edition
EXAMPLE OF SINGLE