Inheritance Introduction
Inheritance Introduction
• Subclasses provide specialized behavior from the basis of common elements provided by the
super class.
• Through the use of inheritance, programmers can reuse the code in the super class many times.
• Once a parent class is written and debugged, it need not be touched again but at the same time
can be revised to work in different situations.
• Reusing existing code saves time and money and increases a program’s reliability.
Cont.
• For example-1, the scooter is a type of the class two-wheelers, which is again a type of (or kind
of) the class motor vehicles
• For example-2, all fruits have a name, a color, and a size. Therefore, Peaches and Guavas also
have a name, a color, and a size.
• We can say that Peaches and Guavas inherit (acquire) these all of the properties of fruit because
they are fruit.
• We also know that fruit undergoes a ripening process, by which it becomes edible.
• Because Peaches and Guavas are fruit, we also know that Peaches and Guavas will inherit the
behavior of ripening.
Cont.
• Put into a diagram, the relationship between Peaches, Guavas, and fruit might look something
like this:
Fruit
Peach Guava
Why use Inheritance?
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Defining Derived Classes
• A derived class can be defined by specifying its SYNTAX
relationship with the base class in addition to its
own details.
• The visibility mode is optional and if present, may
be either private or public
• Visibility mode specifies whether the features of
EXAMPLE
the base class are privately derived or publicly
derived
• The default visibility mode is private
• Some of the base class data elements and
member functions are inherited into the derived
class
• We can add our own data and member functions
and thus extend the functionality of the base class
Single Inheritance
• In single inheritance, a class derives from one base class only. This means that there is only one
subclass that is derived from one superclass.
• Syntax:
Class A
Class B
Multiple Inheritance
• A class can inherit properties from more than one class which is known as multiple inheritances.
Class B Class C
Class A
Multilevel Inheritance
• A class can be derived from another derived class which is known as multilevel inheritance.
Class C
Class B
Class A
Hierarchical Inheritance
• In this type of inheritance, one parent class has more than one child class
Class A
Class B Class C
Class C
Class B Class D
Class A
Hybrid Inheritance