C++ Inheritance

The Inheritance concept in C++ brings the code reuse functionality by using the inherit feature. This allows a class to inherit the members of a class already present. Therefore, the concept of base and derived class is what Inheritance is all about in C++.

Before moving further, let us first understand the concept of Inheritance with the base an derived class:

  • Base class: The base class is the parent class.
  • Derived class: The derived class is the child class since it is derived from the parent class.

Let us now see an example of Inheritance wherein we will create a Derived class from a Base class:

The output is as follows:

In the above example, we have accessed the method of the base class using the derived class object.

The protected Access Specifier

C++ has three access specifiers to access the members of a class. It includes the private, public, and protected. The private and public access specifier, we discussed in the Access Specifiers lesson. Let us now discuss the role of the Protected Access Specifier in C++.

The class members declared as Protected Access Specifiers can be accessed by any derived class of that class. The Kid class can easily access the inherited protected members of the Father class i.e. the base class.

In the below example, the Kid class accesses the inherited protected member age of the Father class i.e. the base class. Let us see the example now:

Output

Multilevel Inheritance

We can further inherit a class i.e., the multilevel inheritance concept. For example,

Above, the GRANDKID class is derived from the KID class, which is derived from the FATHER class.

Remember, the last derived class will have access to all the base class members i.e., the GRANDKID class will have to access to the members of the FATHER and KID classes (base classes).

Let us now see an example to understand Multilevel Inheritance. In this, we have a base class Father. The derived class is the Kid class, which further derives a class Grandkid. Therefore, we have 3 classes:

The output is as follows:

In the above example, we have accessed the method of the base class using the last derived class object.

Multiple Inheritance

We can easily derive a class from more than a single base class. This defines the concept of Multiple Inheritance in C++. A comma-separated list separates multiple base classes as shown below:

Let us now see an example to understand Multiple Inheritance. In this, we have two base classes Father and Mother. Therefore, a single derived class Kid is having two base classes i.e., Father and Mother:

The output is as follows:

C++ Access Specifiers
C++ Classes and Objects
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading