Inheritance In C++

In C++, inheritance is a process in which one object inherits all the properties and behaviors of its parent object automatically. It allows us to reuse, extend, or modify the attributes and behaviors which are defined in other classes.

In C++ , the class that inherits the members of another class is called a derived class, and the class whose members are inherited is called the base class. The derived class is the specialized class for the base class.

Syntax

It has the following syntax:

Example

class derived_class_name :: visibility-mode base_class_name

{

    // body of the derived class.

}

C++ Basic Example of Inheritance

Let us take an example to illustrate the C++ Inheritance.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

// Base Class

class Animal {  

public:  //Access 

    // Base class member function

    void eat() {

        cout << "Animal Sounds" << endl;

    }

};

// Derived Class

class Dog : public Animal {  

public:

    // Derived class member function

    void bark() {

        cout << "Dog Barks" << endl;

    }

};

int main() //Main function

{

    Dog dog;     // Create object of derived class Dog

    dog.eat();   // Call base class function using derived class object

    dog.bark();  // Call derived class function

    return 0;

}

Output:

Output

Animal Sounds

Dog Barks

Explanation

In this example, we have taken a base class Animal that contains an eat function. After that, we take a Dog derived class that is inherited from an Animal and includes its own function, bark. In the main function, an object dog of the Dog class is created. Finally, the dog.eat calls the inherited function from Animal, and dog.bark calls the own function of Dog.

Types of Inheritance Classes in C++

There are mainly two classes of C++ inheritance.

1) Base Classes

A base class is a class that provides common attributes and methods for other classes to inherit. It defines the properties and behaviours that its derived classes can reuse or override, and it serves as the foundation of further class extensions. It serves as a parent and superclass.

Syntax

It has the following syntax

Example

class Base_Class{ 

  // members....

  // member function 

}

2) Derived Classes

A derived class is a class that inherits the properties and behaviors from the base class. It can include some new features or override existing features of the base class. It is also known as child class or subclass.

Syntax

It has the following syntax:

Example

class Derived_class : public Base_class{

  // members....

  // member function 

}

C++ Inheritance Classes Example:

Let us take an example to illustrate the inheritance classes in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class Base {  //Base Class

public:

	int x;

};

class Derived : public Base {  //Derived Class

public:

	int y;

};

int main()  //Main Function

{

	// Initialize a Derived class

	Derived CppTutorial;

	// Assign a value to the Derived class variable

	CppTutorial.y = 10;

	// Assign a value to the Base class variable via derived class

	CppTutorial.x = 15;

	cout << "Derived Class Value: " << CppTutorial.y << endl;

	cout << "Base Class Value: " << CppTutorial.x << endl;

	return 0;

}

Output:

Output

Derived Class Value: 10

Base Class Value: 15

Types of Inheritance

There are mainly five types of inheritance in C++.

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hybrid Inheritance
  • Hierarchical Inheritance

Here, we will discuss all types of inheritance one by one.

1) C++ Single Inheritance

In C++, a single inheritance is defined as the inheritance in which a derived class is inherited from only a base class.

Where 'A' is the base class, and 'B' is the derived class.

Syntax

It has the following syntax:

Example

class Base

 {

    // Body of base class 

};

class Derived : public Base

 {

    // Body of derived class

};

C++ Single Inheritance Example

Let us take an example to illustrate the single inheritance in C++.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

 class Account {   //Base Class

   public:   //Access Modifier

   float salary = 65000;   

 };  

   class Programmer: public Account {   //Derived Class

   public:  

   float bonus = 5500;    

   };       

int main(void) {  //Main Function

     Programmer p1;  

     cout<<"Salary: "<<p1.salary<<endl;    

     cout<<"Bonus: "<<p1.bonus<<endl;    

    return 0;  

}

Output:

Output

Salary: 65000

Bonus: 5500

Explanation

In this example, we have taken a base class, Account and a derived class, Programmer. After that, this program exhibits single inheritance in C++, with the Programmer class inheriting from a single base class Account. The Programmer object p1 has direct access to both the inherited salary and its own bonus.

To Read More: Single Inheritance

2) C++ Multiple Inheritance

In C++, multiple inheritance is the process by which one class may inherit the properties and behaviors of multiple base classes. In this inheritance, a class can inherit from more than one class. It provides greater flexibility and code reusability but also enhances the code complexity.

Syntax

It has the following syntax:

Example

class Base1

{

    //Body of base class 1 

};

 class Base2 

{

    // Body of base class 2 

};

class Derived : public Base1, public Base2 

{

    // Body of the derived class 

};

C++ Multiple Inheritance Example

Let us take a simple example to illustrate the multiple inheritance in C++.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

class A  //Base class A

{  

    protected:  

int a;  //Protected data member

    public:  

 void get_a(int n)  

    {  

        a = n;  

    }  

};  

  

class B  //Base class B

{  

    protected:  

    int b;  

    public:  

    void get_b(int n)  

    {  

        b = n;  

    }  

};  

class C : public A,public B  //Derived Class

{  

   public:  

    void display()  

    {  

        cout << "The value of a is : " <<a<< endl;  

        cout << "The value of b is : " <<b<< endl;  

        cout<<"Addition of a and b is : "<<a+b;  

    }  

};  

int main()  //Main function

{  

   C c;  

   c.get_a(10);  

   c.get_b(20);  

   c.display();  

     return 0;  

}

Output:

Output

The value of a is : 10

The value of b is : 20

Addition of a and b is : 30

Explanation

In this example, class 'C' inherits two base classes, 'A' and 'B', in a public mode. Classes A and B have their own data members and functions. After that, the show method in class C retrieves both inherited values and adds them together for output.

To Read More: Multiple Inheritance

3) C++ Multilevel Inheritance

C++ Multilevel Inheritance is a concept where a class is derived from a derived class, creating a chain of inheritance. There can be any number of levels. Let's consider three classes, such as Class A, B, and C, where class represents the base class, class B represents the intermediator class, and class C represents the Derived class. It shows that one class inherits another class that is further inherited by another class.

Syntax:

It has the following syntax.

Example

class Base

{

    // body of Base class

};

 class Intermediate : public Base 

{

    //Body of intermediate class 

};

class Derived : public Intermediate 

{

    // Body of derived class 

};

C++ Multi Level Inheritance Example

Let's see the example of multilevel inheritance in C++.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

 class Animal {  //Base Class

   public:  //Access Modifier

 void eat() 

{   

cout<<"Eating..."<<endl;   

 }    

   };  

   class Dog: public Animal //intermediator Class

   {    

       public:  

     void bark(){  

    cout<<"Barking..."<<endl;   

     }    

   };   

   class BabyDog: public Dog  //Derived Class

   {    

       public:  

     void weep() {  

    cout<<"Weeping...";   

     }    

};   

int main(void) //Main Function

{  

BabyDog d1;  

    d1.eat();  

d1.bark();  

     d1.weep();  

     return 0;  

   }

Output:

Output

Eating...

Barking...

Weeping...

Explanation

In this example, we demonstrate the multilevel inheritance in C++, where the class BabyDog inherits from Dog, which in turn inherits from Animal. The object d1 of BabyDog may access methods from all three classes, demonstrating inherited behaviours like eating, barking, and weeping.

To Read More: Multilevel Inheritance

4) C++ Hybrid Inheritance

In C++, hybrid inheritance is a combination of more than one type of inheritance. In this inheritance, we can contain elements of single inheritance, multiple inheritance, multilevel, and hierarchical inheritance in the class.

Syntax

It has the following syntax.

Example

class Base 

{

    // base class members and statements

};

class Intermediate1 : public Base

{

    // intermediate class 1 members and statements

};

class Intermediate2 : public Base 

{

    // Body of intermediate class 2 members 

};

class Derived : public Intermediate1, public Intermediate2

 {

    // derived class members and statements

};

C++ Hybrid Inheritance Example

Let us take a simple example to illustrate the hybrid inheritance in C++.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

class A  //Base class

{  

    protected:  

    int a;  

    public:  

    void get_a()  

    {  

       std::cout << "Enter the value of 'a' : " << std::endl;  

       cin>>a;  

    }  

};    

class B : public A   //class B derived from Class A

{  

protected:  

    int b;  

    public:  

    void get_b()  

               {  

        std::cout << "Enter the value of 'b' : " << std::endl;  

       cin>>b;  

    }  

};  

class C   

{  

    protected:  

    int c;  

    public:  

    void get_c()  

    {  

        std::cout << "Enter the value of 'c' : " << std::endl;  

        cin>>c;  

    }  

};    

class D : public B, public C  //class D derived from both class B and Class C

{  

    protected:  

    int d;  

    public:  

    void mul()  

    {  

         get_a();  

         get_b();  

  get_c();  

         std::cout << "Multiplication of a, b, c is : " <<a*b*c<< std::endl;  

    }  

};  

int main()  //Main Function

{  

    D d;  

    d.mul();  

    return 0;  

}

Output:

Output

Enter the value of 'a' :

10              

Enter the value of 'b' :    

20      

Enter the value of 'c' :   

30  

Multiplication of a, b, c is : 6000

To Read More: Hybrid Inheritance

5) C++ Hierarchical Inheritance

In C++, hierarchical inheritance is defined as the process of deriving multiple classes from a single base class. In this inheritance, we can include all features in the base class that are common in child classes.

Syntax

It has the following syntax.

Example

class A  

{  

    // body of the class A.  

}    

class B : public A   

{  

    // body of class B.  

}  

class C : public A  

{  

    // body of class C.  

}   

class D : public A  

{  

    // body of class D.  

}

C++ Hierarchical Inheritance Example

Let us take an example to illustrate the Hierarchical Inheritance in C++.

Example

Example

#include <iostream>  

using namespace std;  

class Shape     // Declaration of base class.  

{  

    public:  

    int a;  

    int b;  

    void get_data(int n,int m)  

    {  

        a= n;  

        b = m;  

    }  

};  

class Rectangle : public Shape  // inheriting Shape class  

{  

    public:  

    int rect_area()  

    {  

        int result = a*b;  

        return result;  

    }  

};  

class Triangle : public Shape    // inheriting Shape class  

{  

    public:  

    float triangle_area()  

    {  

        float result = 0.5*a*b;  

        return result;  

    }  

};  

int main()  //Main Function

{  

    Rectangle r;  

    Triangle t;  

    int length,breadth,base,height;  

    std::cout << "Enter the length and breadth of a rectangle: " << std::endl;  

    cin>>length>>breadth;  

    r.get_data(length,breadth);  

    int m = r.rect_area();  

    std::cout << "Area of the rectangle is : " <<m<< std::endl;  

    std::cout << "Enter the base and height of the triangle: " << std::endl;  

cin>>base>>height;  

 t.get_data(base,height);  

    float n = t.triangle_area();  

    std::cout <<"Area of the triangle is : "  << n<<std::endl;  

    return 0;  

}

Output:

Output

Enter the length and breadth of a rectangle:

23  

20  

Area of the rectangle is : 460          

Enter the base and height of the triangle:  

2   

5

Area of the triangle is : 5

Explanation

In this example, we have taken two derived classes (Rectangle and Triangle) descended from a common base class (Shape). The base class includes a method for inputting dimensions, which the derived classes utilize to calculate and return the area of a rectangle and a triangle.

To Read More: Hierarchical Inheritance

Access Specifiers in Inheritance

In C++, access specifiers can be mainly classified into three categories:

1) Public Inheritance

In public inheritance, all public base class members remain public, while protected elements remain protected in the derived class. It illustrates the true is-a relationship. For example, a car is a vehicle. A car inherits the basic qualities of a vehicle, such as start and stop.

2) Protected inheritance

Protected inheritance ensures that both public and protected base class members are protected in the derived class. Access is limited outside of the derived class. In a real-world example, a StudentRecord secures internal access, such as scores, while allowing for inherited behaviour.

3) Private inheritance

In private inheritance, all public and protected members of the base class are made private in the derived class. It is utilized when the purpose of inheritance is code reuse rather than an is-a relationship.

Visibility of Inherited Members

Here is a table that shows the visibility of inherited members in C++.

Base class visibility Derived class visibility
Public Private Protected
Private Not Inherited Not Inherited Not Inherited
Protected Protected Private Protected
Public Public Private Protected

Effects of Inheritance in C++

In C++, inheritance has impact on different components of a class in distinct ways. Some of these effects are as follows:

1) Static Members and Inheritance

Static members are linked to the class rather than specific objects. All instances of the class share these members and do not participate in conventional inheritance. While a derived class does not inherit static members directly, they are still accessible through the base class's name or the derived class's scope.

2) Inheritance's Friend Functions and Classes

Friend functions and friend classes allow external access to a class's private and protected members. They provide flexibility to inheritance for tightly tied interactions, debugging, operator overloading, and allowing particular access to related functions or utility classes.

3) Constructors and Destructors in Inheritance (C++)

Constructors and destructors are essential parts of the object lifecycle in C++. Constructors and destructors are present in all classes, whether explicitly defined by the programmer or implicitly created by the compiler.

Constructor Behavior in Inheritance

  • The derived class does not inherit constructors.
  • However, the constructor of the base class is automatically invoked when a derived class object is created.
  • The order of constructor execution always follows a top-down approach.
  • First, the base class constructor is executed. After that, the derived class constructor is executed.
  • If the base class constructor accepts parameters, the derived class must call it directly with an initializer list.
  • Destructor Behavior in Inheritance

  • Destructors are not inherited and are called in reverse order of construction.
  • First, the destructor for the derived class is executed, and then the base class's destructor is invoked.
  • It ensures that the derived class's resources get released before those of the base class.
  • C++ Destructor Inheritance Example

Let's now look at a C++ example of destructor behavior in inheritance.

Example

Example

#include <iostream>

using namespace std;

class Parent 

{

public:

   Parent() 

    {

        cout << "Parent class constructor is executed" << endl;

    }

    ~Parent() 

    {

        cout << "Parent class destructor is executed" << endl;

    }

};

class Child : public Parent 

{

public:

    Child()

    {

        cout << "Child class constructor is executed" << endl;

    }

   ~Child()

    {

        cout << "Child class destructor is executed" << endl;

    }

};

int main() 

{

    Child instance;

    return 0;

}

Output:

Output

Parent class constructor is executed

Child class constructor is executed

Child() class destructor is executed

Parent class destructor is executed

Explanation

In this example, when we create a Child class object, the Parent class constructor is called first, and then the Child class constructor. When the program terminates, destructors are called in reverse order: first, the Child destructor, the Parent destructor, which indicates the lifecycle order of inherited classes.

Polymorphism in Inheritance

In C++ inheritance, polymorphism allows us to redefine a base class member function in a derived class, which is known as function overriding. It is an essential feature of runtime polymorphism, in which the function to be performed is determined at runtime rather than compile time.

C++ Polymorphism in Inheritance Example

Let's now look at a C++ example of polymorphism in inheritance.

Example

Example

#include <bits/stdc++.h>

using namespace std;

class Base

{

public:

    void print()

    {

        cout << "Base Function" << endl;

    }

};

class Derived : public Base {

public:

    void print() {

        cout << "It is a Derived Function.";

    }

};

int main() 

{

    Derived d_object;

    d_object.print();

    return 0;

}

Output:

Output

It is a Derived Function.

Explanation

In this example, the Derived class redefines the print function that was initially declared in the Base class. When the print function is called on the Derived class object d_object, the overridden version in the Derived class is performed, which results in the output "It is a Derived Function".

C++ Inheritance MCQs

1) What is C++'s default inheritance mode for classes?

  • Public
  • Private
  • Protected
  • None

2) Can a derived class have direct access to a base class's private members?

  • Only if public inheritance
  • Only if base is friend

3) What is the public inheritance model?

  • Has a relationship.
  • Uses a relationship.
  • Owns a relationship.
  • Is a relationship.

4) What happens to the base class's public members when private inheritance occurs?

  • Stay public
  • Be protected
  • Become private
  • Not inherit

5) Which access specifier allows a base class member to be accessible only within derived classes rather than outside?

  • Public
  • Private
  • A friend
  • Protected

Input Required

This code uses input(). Please provide values below: