Detailed Guide to Inheritance in C++

In C++, inheritance is the process by which an object automatically acquires all the properties and behaviors of its parent object. Through inheritance, you can reuse, extend, or modify the properties and behaviors defined in other classes.

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

Advantages of C++ Inheritance

Code Reusability: You can now reuse the members of the parent class. Therefore, there is no need to redefine members. As a result, less code is required in the class.

👇Click to receive👇
👉C Language Knowledge Resource Collection

Types of Inheritance

C++ supports five types of inheritance:

  • Single Inheritance

  • Multiple Inheritance

  • Hierarchical Inheritance

  • Multilevel Inheritance

  • Hybrid Inheritance

Detailed Guide to Inheritance in C++

Derived Class

A derived class is defined as a class that is derived from a base class.

Syntax of Derived Class:

class DerivedClassName : AccessModifier BaseClassName {// Body of the derived class.}

Where,

DerivedClassName: The name of the derived class.

Access Modifier: The access modifier specifies whether the base class is publicly or privately inherited. It can be public or private.

BaseClassName: The name of the base class.

  • When the base class is privately inherited, the public members of the base class become private members of the derived class. Therefore, objects of the derived class cannot access the public members of the base class and can only access them through the member functions of the derived class.

  • When the base class is publicly inherited, the public members of the base class also become public members of the derived class. Therefore, objects of the derived class and member functions of the base class can access the public members of the base class.

Note:

  • In C++, the default visibility is private.

  • Private members of the base class are never inherited.

C++ Single Inheritance

Single inheritance is defined as inheritance where the derived class inherits from only one base class.

Detailed Guide to Inheritance in C++

Where ‘A’ is the base class and ‘B’ is the derived class.

C++ Single Level Inheritance Example:

Field Inheritance When one class inherits from another class, it is called single-level inheritance. Let’s look at an example of single-level inheritance that only inherits fields.

#include <iostream>
using namespace std;
class Account {
  public:
  float salary = 60000;
};
class Programmer: public Account {
  public:
  float bonus = 5000;
};
int main(void) {
  Programmer p1;
  cout<<"Salary: "<<p1.salary<<endl;
  cout<<"Bonus: "<<p1.bonus<<endl;
  return 0;
}

Output:

Salary: 60000
Bonus: 5000

In the above example, Employee is the base class, and Programmer is the derived class.

C++ Single Level Inheritance Example: Inheriting Methods

Let’s look at another example of inheritance in C++ that only inherits methods.

#include <iostream>
using namespace std;
class Animal {
  public:
  void eat() {
    cout<<"Eating..."<<endl;
  }
};
class Dog: public Animal  {
  public:
  void bark(){
    cout<<"Barking...";
  }};
int main(void) {
  Dog d1;
  d1.eat();
  d1.bark();
  return 0;
}

Output:

Eating...Barking...

Let’s look at a simple example.

#include <iostream>
using namespace std;
class A  {
    int a = 4;
    int b = 5;
    public:
    int mul()  {
        int c = a*b;
        return c;
    }
};
class B : private A  {
    public:
    void display()  {
        int result = mul();
        std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
    }
};
int main()  {
    B b;
    b.display();
    return 0;
}

Output:

Multiplication of a and b is : 20

In the above example, class A is privately inherited. Therefore, the object of class B cannot access the mul() function of class A. Only the member functions of class B can access it.

How to Make Private Members Inheritable

Private members are not inheritable. If we change their visibility to public, it cancels the advantage of data hiding.

C++ introduces a third visibility modifier, called protected. Members declared as protected can be accessed by all member functions within the class as well as by classes directly derived from it.

Visibility modifiers can be divided into three categories:

Detailed Guide to Inheritance in C++

  • Public: When a member is declared public, it can be accessed by all functions in the program.

  • Private: When a member is declared private, it can only be accessed within the class.

  • Protected: When a member is declared protected, it can be accessed both within its own class and in classes directly derived from it.

Visibility of Inherited Members

Base Class Visibility Derived Class Visibility
Public Private Protected
Private Not Inheritable Not Inheritable Not Inheritable
Protected Protected Private Protected
Public Public Private Protected

C++ Multilevel Inheritance

Multilevel inheritance is the process of deriving another derived class from one derived class.

Detailed Guide to Inheritance in C++

C++ Multilevel Inheritance Example

When one class inherits from another class, which in turn is inherited by another class, it is called multilevel inheritance in C++. Inheritance is transitive, so the last derived class will inherit all members of the base classes.

Let’s look at an example of multilevel inheritance in C++.

#include <iostream>
using namespace std;
class Animal {
    public:
    void eat() {
        cout<<"Eating..."<<endl;
    }
};
class Dog: public Animal {
    public:
    void bark(){
        cout<<"Barking..."<<endl;
    }
};
class BabyDog: public Dog {
    public:
    void weep() {
        cout<<"Weeping...";
    }
};
int main(void) {
    BabyDog d1;
    d1.eat();
    d1.bark();
    d1.weep();
    return 0;
}

Output:

Eating...Barking...Weeping...

C++ Multiple Inheritance

Multiple inheritance is the process of deriving a new class from two or more classes.

Detailed Guide to Inheritance in C++

Syntax of Derived Class:

class D : Visibility B-1, Visibility B-2, ?{// Class content;}

Let’s look at a simple example of multiple inheritance.

#include <iostream>
using namespace std;
class A {
    protected:
    int a;
    public:
    void get_a(int n) {
        a = n;
    }
};
class B {
    protected:
    int b;
    public:
    void get_b(int n) {
        b = n;
    }
};
class C : public A, public B {
    public:
    void display() {
        std::cout << "Value of a: " << a << std::endl;
        std::cout << "Value of b: " << b << std::endl;
        cout << "The sum of a and b is: " << a + b;
    }
};
int main() {
    C c;
    c.get_a(10);
    c.get_b(20);
    c.display();
    return 0;
}

Output:

Value of a: 10
Value of b: 20
The sum of a and b is: 30

In the above example, class ‘C’ publicly inherits two base classes ‘A’ and ‘B’.

Resolving Ambiguity in Inheritance

When functions with the same name appear in two or more base classes in multiple inheritance, ambiguity arises.

Understand this through the following example:

#include <iostream>
using namespace std;
class A {
    public:
    void display() {
        std::cout << "Class A" << std::endl;
    }
};
class B {
    public:
    void display() {
        std::cout << "Class B" << std::endl;
    }
};
class C : public A, public B {
    void view() {
        display();
    }
};
int main() {
    C c;
    c.display();
    return 0;
}

Output:

Error: Reference to 'display' is ambiguous

The above problem can be resolved by using the class scope operator. In the above example, the derived class code can be rewritten as:

class C : public A, public B {
    void view() {
        A::display(); // Calls the display() function of class A.
        B::display(); // Calls the display() function of class B.
    }
};

Ambiguity can also occur in single inheritance.

Consider the following situation:

class A {
    public:
    void display() {
        cout << "Class A" << endl;
    }
};
class B {
    public:
    void display() {
        cout << "Class B" << endl;
    }
};

In the above case, the function of the derived class overrides the method of the base class. Therefore, calling the display() function will simply call the function defined in the derived class. If we want to call the base class function, we can use the class scope operator.

int main() {
    B b;
    b.display(); // Calls the display() function of class B.
    b.B::display(); // Calls the display() function defined in class B.
}

C++ Hybrid Inheritance

Hybrid inheritance is a combination of multiple types of inheritance.

Detailed Guide to Inheritance in C++

Let’s look at a simple example:

#include <iostream>
using namespace std;
class A {
    protected:
    int a;
    public:
    void get_a() {
        cout << "Enter the value of 'a': " << endl;
        cin>>a;
    }
};
class B : public A {
    protected:
    int b;
    public:
    void get_b() {
        cout << "Enter the value of 'b': " << endl;
        cin>>b;
    }
};
class C {
    protected:
    int c;
    public:
    void get_c() {
        cout << "Enter the value of 'c': " << endl;
        cin>>c;
    }
};
class D : public B, public C {
    protected:
    int d;
    public:
    void mul() {
        get_a();
        get_b();
        get_c();
        cout << "Product of a, b, and c is: " <<a*b*c<< endl;
    }
};
int main() {
    D d;
    d.mul();
    return 0;
}

Output:

Enter the value of 'a': 10
Enter the value of 'b': 20
Enter the value of 'c': 30
Product of a, b, and c is: 6000

C++ Hierarchical Inheritance

Hierarchical inheritance is the process of deriving two or more classes from one base class.

Detailed Guide to Inheritance in C++

Syntax of Hierarchical Inheritance:

class A  {
    // Content of class A.
}
class B : public A {
    // Content of class B.
}
class C : public A {
    // Content of class C.
}
class D : public A {
    // Content of class D.
}

Let’s look at a simple example:

#include <iostream>
using namespace std;
class Shape                 // Declare base class.
{
    public:
    int a;
    int b;
    void get_data(int n,int m) {
        a= n;
        b = m;
    }
};
class Rectangle : public Shape  // Inherit Shape class
{
    public:
    int rect_area() {
        int result = a*b;
        return result;
    }
};
class Triangle : public Shape    // Inherit Shape class
{
    public:
    int triangle_area() {
        float result = 0.5*a*b;
        return result;
    }
};
int main() {
    Rectangle r;
    Triangle t;
    int length,breadth,base,height;
    cout << "Enter the length and width of the rectangle:" << endl;
    cin>>length>>breadth;
    r.get_data(length,breadth);
    int m = r.rect_area();
    cout << "Area of rectangle: " <<m<< endl;
    cout << "Enter the base and height of the triangle:" << endl;
    cin>>base>>height;
    t.get_data(base,height);
    float n = t.triangle_area();
    cout <<"Area of triangle: "  << n<<endl;
    return 0;
}

Output:

Enter the length and width of the rectangle: 23  20
Area of rectangle: 460
Enter the base and height of the triangle: 2  5
Area of triangle: 5

Detailed Guide to Inheritance in C++


 Popular Recommendations
  • CLion Tutorial – Installing CMake in CLion

  • C Language Algorithm – “Search Rotated Sorted Array II” Algorithm Problem

  • C++ Tutorial – Detailed Explanation of Mathematical Functions in C++

Leave a Comment