Inheritance in C++

One of the most important features of Object-Oriented Programming is Inheritance. In this article, we will learn all about inheritance in C++.

What is Inheritance in C++

Inheritance refers to the ability of a class to derive features and traits from another class.

Base Class: The class whose features are inherited is called the super class or the base class or the parent class.

Derived Class: The class that inherits the features is called the sub class or the derived class or the child class.

Let’s consider classes of computer science engineers and electrical engineers. Both of these are inherited from a class of engineers. This is a real life example of inheritance.

Inheritance implements an is-a relationship. For example, a boy is a human, a lily is a flower, etc.

Use of Inheritance in C++

If there are three sections A, B and C in a school, the classes for these sections will have the same functions like students(), timetable(), classteacher(), etc. Without inheritance, we will have to define these functions in all three classes. Thus, writing the same code thrice.

Programming without Inheritance

As a solution, we use inheritance which

  • Increases the reusability of code
  • Eliminates duplication
  • Increases the reliability of code as it provides a definite structure to our programs
  • Brings transitive nature

Hence, our program becomes simple by creating a base class school.
Programming with inheritance

Follow TechVidvan on Google & Stay updated with latest technology trends

Implementation of Inheritance in C++

Syntax to create a derived class:

class derivedclass_name : access_specifier baseclass_name {
//body of derived class
};

Here,

  • derivedclass_name is the name given to the derived class
  • baseclass_name is the name of the base class
  • access_specifier specifies the mode of inheritance. It is public, private or protected.

Access Control in C++

It is not possible for a derived class to directly access private members of its base class. However, it gets a complete object of base class which contains the private members. The derived class can also access private members of the base class through its public and protected members.

A derived class does not inherit

  • Constructors and destructors of the base class
  • Friend classes and friend functions of the base class
  • Overloaded operators of the base class

Modes of Inheritance in C++

1. Public inheritance in C++

If a derived class is inherited from a public base class, the base class’s public members become public and protected members become protected in the derived class.

2. Protected Inheritance in C++

If we inherit a derived class from a protected base class, the base class’s public as well as protected members become protected in the derived class.

3. Private Inheritance in C++

If a derived class is inherited from a private base class, both public and protected members of the base class become private in the derived class.

For every mode of inheritance, the table below shows the access control of base class members in a derived class.

Base Class MemberMode of Inheritance
PublicProtectedPrivate
PublicPublicProtectedPrivate
ProtectedProtectedProtectedPrivate
PrivatePrivatePrivatePrivate

Types of Inheritance in C++

There are 5 types of C++ Inheritance:

1. Single Inheritance in C++

In this type of inheritance, there is only one derived class inherited from one base class.

Single inheritance in C++

Syntax:

class base {
//Body of the base class
};
class derived : access_specifier base {
//Body of the derived class
};

Example of Single Inheritance in C++

#include <iostream>
using namespace std;

class Animal {
    public:
        void fun1() {
            cout<<"I am an animal"<<endl;
        }
};

class Dog : public Animal {
    public:
        void fun2() {
            cout<<"I am a dog"<<endl;
        }
};

int main() {
  Dog obj;
  obj.fun1();
  obj.fun2();
  return 0;
}

Output

I am an animal
I am a dog

2. Multiple Inheritance in C++

In this type of inheritance, one derived class inherits from more than one base class.

Multiple Inheritance in C++

Syntax:

class base1 {
  //body
};
class base2 {
  //body
};
.
.
.
class derived : access_specifier base1, access_specifier base2, ... {
  //body of the derived class
};

Example of Multiple Inheritance in C++

#include <iostream>
using namespace std;

class A {
    protected:
    int a;
    public:
    void seta(int x) {
        a = x;
    }
};

class B {
    protected:
    int b;
    public:
    void setb(int y) {
        b = y;
    }
};
class C : public A, public B {
    public:
    int add() {
        cout<<"Addition of two numbers = "<<a+b;
    }
};

int main() {
  C obj;
  obj.seta(4);
  obj.setb(9);
  obj.add();
  return 0;
}

Output

Addition of two numbers = 13

3. Multilevel Inheritance in C++

A derived class inherits from another derived class in this type of inheritance.

Multilevel Inheritance in C++

Syntax:

class C {		//Base Class
  //body
};
class B : access_specifier C {			//Derived from C
  //body
};
class A : access_specifier B {			//Derived from B
  //body
};

Example of Multilevel Inheritance in C++

#include <iostream>
using namespace std;

class Animal {
    public:
    void fun1() {
        cout<<"Animal"<<endl;
    }
};

class PetAnimal : public Animal {
    public:
    void fun2() {
        cout<<"Pet animal"<<endl;
    }
};

class Dog : public PetAnimal {
    public:
    void fun3() {
          fun1();
        fun2();
        cout<<"Dog"<<endl;
    }
};

int main() {
  Dog obj;
  obj.fun3();
  return 0;
}

Output

Animal
Pet animal
Dog

4. Hierarchical Inheritance in C++

Multiple derived classes are inherited from a single base class in this type of inheritance.

Hierarchical Inheritance in C++

Syntax:

class base {
  //body
};
class derived1 : access_specifier base {
  //body;
};
class derived2 : access_specifier base {
  //body;
};

Example of Hierarchical Inheritance in C++

#include <iostream>
using namespace std;

class Values {
    protected:
    double a, b;
    public:
    void initialize(double x, double y) {
        a = x;
        b = y;
    }
};

class A : public Values {
    public:
    void add() {
        cout<<"addition = "<<a+b<<endl;
    }
};

class B : public Values {
    public:
    void subtract() {
        cout<<"subtraction = "<<a-b<<endl;
    }
};

int main() {
  A obj1;
  B obj2;
  obj1.initialize(4.5,8.7);
  obj1.add();
  obj2.initialize(3.6,11);
  obj2.subtract();
  return 0;
}

Output

addition = 13.2
subtraction = -7.4

5. Hybrid Inheritance in C++

Hybrid inheritance is the combination of two or more types of inheritance. We can make various combinations in hybrid inheritance.

For example, a combination of hierarchical and multiple inheritance (commonly called multipath inheritance) as shown in the image below.

Hybrid Inheritance in C++

Example of Hybrid Inheritance in C++

#include <iostream>
using namespace std;

class A {
    protected:
    float a;
    public:
    void seta(float n1) {
        a = n1;
    }
};

class B : public A {
    public:
    void modifyA() {
        a/=2;
    }
};

class C {
    protected:
    float c;
    public:
    void setc(float n2) {
        c = n2;
    }
};

class D : public B, public C {
    public:
    float modify() {
        modifyA();
        cout<<"Result = "<<a*c;
    }
};

int main() {
  D obj;
  obj.seta(15.6);
  obj.setc(9.7);
  obj.modify();
  return 0;
}

Output

Result = 75.66

Avoiding Ambiguity in Inheritance

In some cases of inheritance, the compiler faces ambiguity. An example of such a case is

Example of Ambiguity in Inheritance

#include <iostream>
using namespace std;

class A {
    protected:
    int a;
};
class B : public A {

};
class C : public A {

};
class D : public B, public C {
    public:
    void fun() {
        a=7;       //ambiguity
    } 
    void display() {
        cout<<"a from B = "<<a<<endl;
        cout<<"a from C = "<<a<<endl; 
    }
};
int main() {
  D obj;
  obj.fun();
  obj.display();
  return 0;
}

We get a compilation error stating reference to ‘a’ is ambiguous.

This happened because class D has two copies of variable a, one via class B and other via class C.

We can avoid such ambiguity in two ways.

1. Using scope resolution operator (::)

Example of avoiding ambiguity using scope resolution operator (::)

#include <iostream>
using namespace std;

class A {
    protected:
    int a;
};
class B : public A {

};
class C : public A {

};
class D : public B, public C {
    public:
    void fun() {
        B::a=7;
        C::a=10;
    }
    void display() {
        cout<<"a from B = "<<B::a<<endl;
        cout<<"a from C = "<<C::a<<endl;        
    }
};
int main() {
  D obj;
  obj.fun();
  obj.display();
  return 0;
}

Output

a from B = 7
a from C = 10

Note that here, class D has two copies of class A.

2. Using the virtual base class

Example of avoiding ambiguity using virtual base class

#include <iostream>
using namespace std;

class A {
    protected:
    int a;
};
class B : virtual public A {

};
class C : virtual public A {

};
class D : public B, public C {
    public:
    void fun() {
        a = 7;
    }
    void display() {
        cout<<"a from B = "<<a<<endl;
        cout<<"a from C = "<<a<<endl;        
    }
};
int main() {
  D obj;
  obj.fun();
  obj.display();
  return 0;
}

Output

a from B = 7
a from C = 7

Here, class D contains a single copy of class A. This implies that both class B and C share the same copy of variable a.

Summary

This article covers the concept of inheritance, which is one of the most significant features of OOPs. We learnt why it is important. Then, we covered how to implement inheritance in C++.

There are 5 types of inheritance namely, single, multiple, multilevel, hierarchical and hybrid inheritance. We learnt about all these types of inheritance with suitable examples. We may get a compilation error due to ambiguity in some cases of inheritance. This can be solved using scope resolution operator (::) or virtual base class.

If you are Happy with TechVidvan, do not forget to make us happy with your positive feedback on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *