c++

Inheritance in C++

Inheritance is the key features of "Object-oriented programming" in C++.

The capability of a class to derive properties and characteristics from another class is called Inheritance.

Sun class: The class that inherits properties from another class is called Sub class or Derived Class.

Super class: The class whose properties are inherited by sub class is called Base Class or Super class.


Why &When inheritance should be used in our program ?

Consider a group of Human Being. You need to create classes for Hindi teacher, cricketer and business man. The methods Run(), Eat(), will be same for all of the three classes. If we create these classes avoiding inheritance then we have to write all of these functions in each of the three classes as shown below :

Hindi Teacher Cricketer Business Man
Eat() Eat() Eat()
Run() Run() Run()
Teach() Play Cricket() Run Business()

Although, all of the characters are human being , they can perform daily activity . They also have some special skills.

You can separately create three classes, who can walk, talk and perform their special skill.

Using inheritance, we have to write the functions only one time instead of three times as we have inherited rest of the three classes from base class(Human Being).

In above 3 classes, you can write the same code for walk and talk for each character.

If you want to new feature other than inherited one like eat, then you need to implement the same code for each character.

It'd be a lot easier if we had a “Person” class with basic features like talk, walk, eat, sleep, and add special skills to those features as per our characters. This can be done easily using inheritance.

While using inheritance, we do not implement the same codes for walk and talk for each class. You just need to “inherit” them.

Now, for “Hindi teacher” (derived class), you inherit all features of a Person (base class) and add a new feature “Teach Hindi”.

Similarly, for a footballer, you inherit all the features of a Person and add a new feature “Play Cricket”.

It is important to remember that, each derived class should satisfy the condition whether it "is a" base class or not.


How to implement Inheritance in C++ Programming?

// C++ program to demonstrate implementation of Inheritance
#include <stdio.h>

using namespace std;

// Base class
class Parent {
    public:
        int id_p;
};

// Sub class inheriting from Base Class(Parent)
class Child : public Parent {
    public:
        int id_c;
};

// main function
int main() {
    Child obj1;

    // An object of class child has all data members
    // and member functions of class parent
    obj1.id_c = 10;
    obj1.id_p = 94;

    cout << "Child id is " << obj1.id_c << endl;
    cout << "Parent id is " << obj1.id_p << endl;

    return 0;
}

Output :

Child id is 10
Parent id is 94

In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.

Mode of inheritance :

  1. Public mode: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class.
  2. Protected mode: If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class.
  3. Private mode: If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class.

Example :Creating game characters using the concept of inheritance

#include <iostream>

using namespace std;
class Person
{
    public:
        string profession;
        int age;
        Person(): profession("under age"), age(15) { }
    void display()
    {
        cout << "My profession is: " << profession << endl;
        cout << "My age is: " << age << endl;
        walk();
        talk();
    }
    void run()
    {
        cout << "I can run." << endl;
    }
    void read()
    {
        cout << "I can read." << endl;
    }
};

class hindi Teacher: public Person
{
    public:
        void teach Hindi()
        {
            cout << "I can teach Hindi." << endl;
        }
};

class cricketer: public Person
{
    public:
        void play cricket()
        {
            cout << "I can play cricket." << endl;
        }
};

int main() 
{
    Hindi Teacher teacher;

    teacher.profession = "Teacher";
    teacher.age = 24;
    teacher.display();
    teacher.teachhindi();

    cricket criceter;

    cricketer.profession = "Footballer";
    cricketer.age = 19;
    cricketer.display();
    cricketer.play cricket();

    return 0;
}

Output :

My profession is: Teacher
My age is: 24
I can run.
I can eat.
I can teach Hindi.
My profession is: cricketer
My age is: 20
I can run.
I can eat.
I can play cricket.
  1. Both “Hindi Teacher” and “Cricketer” can access all data members and member functions of “Person”.
  2. Since, Hindi Teacher and Footballer have their own member functions as well: teach-hindi() and play-cricket() respectively.
  3. These functions are only accessed by their own class.

The below table summarizes the above three modes and shows the access specifier of the members of base class in the sub class when derived in public, protected and private modes :


Types of Inheritance in C++

  1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is inherited by one base class only.

    Syntax :

    class subclass_name : access_mode base_class
    {
        // body of subclass
    };

    C++ program to explain single inheritance

    // Single inheritance
    #include <iostream>
    
    using namespace std;
    
    // base class
    class Vehicle {
        public:
            Vehicle()
            {
                cout << "This is a Vehicle" << endl;
            }
    };
    
    // sub class derived from two base classes
    class Car: public Vehicle{
    };
    
    // main function
    int main()
    {
        // creating object of sub class will
        // invoke the constructor of base classes
        Car obj;
        return 0;
    }

    Output :

    This is a vehicle
  2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub class is inherited from more than one base classes.

    Syntax :

    class subclass_name : access_mode base_class1, access_mode base_class2, ....
    {
        //body of subclass
    };

    Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for every base class must be specified.

    C++ program to explain multiple inheritance

    #include <iostream>
    
    using namespace std;
    
    // first base class
    class Vehicle {
        public:
            Vehicle()
            {
                cout << "This is a Vehicle" << endl;
            }
    };
    
    // second base class
    class FourWheeler {
        public:
        FourWheeler()
        {
            cout << "This is a 4 wheeler Vehicle" << endl;
        }
    };
    
    // sub class derived from two base classes
    class Car: public Vehicle, public FourWheeler {
    };
    
    // main function
    int main()
    {
        // creating object of sub class will
        // invoke the constructor of base classes
        Car obj;
        return 0;
    }

    Output :

    This is a Vehicle
    This is a 4 wheeler Vehicle
  3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class.

    C++ program to implement Multilevel Inheritance

    #include <iostream>
    
    using namespace std;
    
    // base class
    class Vehicle
    {
        public:
            Vehicle()
            {
                cout << "This is a Vehicle" << endl;
            }
    };
    
    class fourWheeler: public Vehicle
    { 
        public:
        fourWheeler()
        {
            cout << "Objects with 4 wheels are vehicles" << endl;
        }
    };
    
    // sub class derived from two base classes
    class Car: public fourWheeler {
        public:
        car()
        {
            cout << "Car has 4 Wheels" << endl;
        }
    };
    
    // main function
    int main()
    {
        //creating object of sub class will
        //invoke the constructor of base classes
        Car obj;
    
        return 0;
    }

    Output :

    This is a Vehicle
    Objects with 4 wheels are vehicles
    Car has 4 Wheels
  4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more than one derived class is created from a single base class.

    C++ program to explain Hierarchical inheritance

    #include <iostream>
    
    using namespace std;
    
    // base class
    class Vehicle
    {
        public:
            Vehicle()
            {
                cout << "This is a Vehicle" << endl;
            }
    };
    
    // first sub class
    class Car: public Vehicle {
    };
    
    // second sub class
    class Bus: public Vehicle {
    };
    
    // main function
    int main()
    {
        // creating object of sub class will
        // invoke the constructor of base class
        Car obj1;
    
        Bus obj2;
    
        return 0;
    }

    Output :

    This is a Vehicle
    This is a Vehicle
  5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.

    Below image shows the combination of hierarchical and multiple inheritance.

    C++ program to explain Hybrid inheritance

    #include <iostream>
    
    using namespace std;
    
    // base class
    class Vehicle
    {
        public:
            Vehicle()
            {
                cout << "This is a Vehicle" << endl;
            }
    };
    
    //base class
    class Fare
    {
        public:
            Fare()
            {
                cout<<"Fare of Vehicle\n";
            }
    };
    
    // first sub class
    class Car: public Vehicle {
    };
    
    // second sub class
    class Bus: public Vehicle, public Fare {
    };
    
    // main function
    int main()
    {
        // creating object of sub class will
        // invoke the constructor of base class
        Bus obj2;
    
        return 0;
    }

    Output :

    This is a Vehicle
    Fare of Vehicle

Access specifiers in Inheritance :-
  1. When we create a derived class from a base class, we can use different access specifiers to inherit the data members of the base class.
  2. These can be public, protected or private
  3. As shown in the above example, the base class Person has been inherited publicly by Hindi Teacher and cricketer
Member Function Overriding in Inheritance :-

When the, base class and derived class have member functions with same name and arguments.

If you create an object of the derived class and try to access that member function, the member function in derived class is only invoked.

The member function of derived class overrides the member function of base class.