inheritance in c++ with example program

What is Inheritance?

The basic philosophy behind Object Orientation is to represent things as they exist in the real world. For example, unlike procedural programming languages. C++ treats everything as an object. Like objects exist in the real world, objects in C++ contain properties i.e. members and behavioral attributes i.e. methods. Similarly, another concept has been implemented in C++ based on the real world –inheritance.

Inheritance is the concept by which the properties of one entity are available to another. It allows new classes to be built from older and less specialized classes instead of beginning rewritten from scratch. Looking at the real-life part of it, a child inherits his looks, mannerisms, and qualities from his parents. In order to simulate this environment, C++ allows a class to inherit properties and functions from another. The class that inherits properties and function is called the subclass or the derived class and the class from which they are inherited is called the superclass or the base class. The derived class inherits all the properties of the base class and can add properties and refinements of its own. The base class remains unchanged.

In the above diagram, B inherits from A which consists of data members one, two, three and four. All these members are inherited by B. Apart from this, B’s own data members include five, six and seven. This is pictorially represented given below. Any class can be a base class. More than one class can be derived from a single base class and vice versa. A derived class can also act as a base class for another class.
Assuming that class A already exists, the general format for inheriting class B from A is as follows:

class B : pubic A
{
  private:
  -----
  -----
  public:
  ------
};

In the above declaration, the single(‘:’) is used to specify that the class begins declared is derived from another class(the name of which is specified after the colon). The keyword ‘public‘ follows the colon, and it is an access qualifier used to specify what kind of an inheritance it is. If it is a public inheritance, it means that the public members of the base class are brought into the derived class as public members. However, there is one drawback here. In the previous section, we had mentioned that private members of a class cannot be accessed outside the class definition. This holds true even for derived classes. Even though all the data members and methods of class A are derived by class B, the private data members of class A still remain private to B. The idea behind this is never to compromise on the concept of encapsulation enforced by data hiding. For the sake of understanding, just assume that a derived class is given special privileges and private members are made accessible to derived class alone. If this is done, the strong wall of encapsulation can be shattered simply by creating a dummy derived class.

On the other hand, the members of a base class cannot be declared private just so that they can be accessed in the derived class, for this beats the entire purpose of encapsulation, as they can be accessed anywhere from the program as well. For this purpose, C++ introduces another access specifier – protected.

The members of a class declared as protected can be accessed from the derived classes, but cannot be accessed from anywhere in other classes or the main program. In short, protected members behave like public members when it comes to derived classes, and private members with respect to the rest of the program.

Finally, Inheritance of a base class with visibility mode public, by a derived class, causes public members of the base class to become public members of the derived class and the protected members of the base class become protected members of the derived class. Inheritance of a base class with visibility mode private by a derived class, causes public members of the base class to become private members of the derived class and the protected members of the base class become private members of the derived class. Member functions and objects of a derived class can treat these derived members as though they are defined in the derived class with the private modifier. Thus objects of a derived class cannot access these members.

Qualifierprivateprotectedpublic
privateprivateprivateprivate
protectedprivateprotectedprotected
publicprivateprotectedpublic

Types of Inheritance in C++

The derived class inherits some or all of the traits from the base class. A class can also inherit properties from more than one class or from more than one level. A derived class with only one base is called single inheritance and one with several base classes is called multiple inheritances. On the other hand, the traits of one class may be inherited by more than one class. These processes are known as hierarchical inheritance.

The mechanism of deriving a class from another ‘derived class‘ is known as multilevel inheritance. Below diagrams shows various forms of inheritance that could be used for writing extensible programs. The direction of the arrow indicates the direction of inheritance.
Inheritance is classified into the following forms:

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

Single Inheritance

Derivation of a class from only one base class is called single inheritance.

class A
{
   body of A class
};

class B: public A
{
   body of B class
};

Multiple Inheritance

Derivation of a class from several (two or more) base classes are called multiple inheritances.

class A 
{
  //Body of Class A
};

class B 
{
  //Body of Class B
};

Class C: public A, public B 
{
  //Body of Class C;
};

Hierarchical Inheritance

Derivation of several classes from a single base class i.e, the traits of one class may be inherited by more than one class, is called hierarchical inheritance.

class A
{ 
  //Body of A
};

class B:class A
{ 
   //Body of B
};

class C:class A
{ 
   //Body of C
};

class D:class A
{ 
  //Body of D
};

Multilevel inheritance

Derivation of a class from another derived class is called multilevel inheritance.

class A
{ 
   //Body of A
};

class B:public A
{ 
    //Body of B
};

class C:public B
{ 
   //Body of C
};

Hybrid Inheritance

Derivation of a class involving more than one form of inheritance is known as hybrid inheritance.

class A
{
  //Body of A; 
};

class B: public A
{
 //Body of B; 
};

class C
{ 
  //Body of C; 
};

class D:public B,public C
{ 
  //Body of D; 
};

Multipath Inheritance

Derivation of a class from other derived classes, which are derived from the same base class is called multipath inheritance.

class A 
{ 
   //Body of A
};

class B: public A
{ 
   //Body of  
}

class C: public A
{ 
  //Body of C
};

class D:public B, public C
{ 
  //Body of D
}

Defining Derived Classes 

A derived class can be defined by specifying its relationship with the base class in addition to its own details. The general form of defining a derived class is :

class derived-class-name : visibility-mode base-class-name
{
   //members of derived class
   //methods of derived class
};

Here the colon indicates that the derived-class-name is derived from the base-class-name. The visibility-mode is optional and, if present, may be either private or public. The default visibility-mode is private. Visibility mode specifies whether the features of the base class are privately derived or publicly derived.

class ABC : private XYZ /private derivation
{ 
   //Members of ABC
};

class ABC : public XYZ // public derivation
{ 
   //Members of ABC;
};

class ABC : XYZ // private derivation by default
{ 
  //Members of ABC;
};

Public inheritance

When a derived class publicly inherits the base class, all the public members of the base class also become public to the derived class and the objects of the derived class can access the public members of the base class. 
The following program will illustrate the use of the single inheritance. 


/* This program has a base class Rectangle, from which class Rectangle1 is inherited publicly.*/
#include <iostream>

using namespace std;

class Rectangle {
    private:        // This can't be inherited
     float length ; 
    public:         // The data and member functions are inheritable
     float breadth ; 
     void Enter_lb(void)
     {
         cout << "\n Enter the length of the rectangle : "; 
         cin >> length ;
         cout << "\n Enter the breadth of the rectangle : "; 
         cin >> breadth ; 
     }
    float Enter_l(void)
    { 
        return length ; 
    }
}; // End of the class definition 

class Rectangle1 : public Rectangle 
{ 
    private:
        float area;
    public:
        void Rec_area(void)
        { 
            area = Enter_l() * breadth; // area = length * breadth; 
        }
        void Display(void)
        {
            /*
                -Object of the derived class can't inherit the private member of the base class. 
                -Thus the member function is used here to get the value of data member 'length'.
            */
            cout << "\n Length = " << Enter_l() ; 
            cout << "\n Breadth = " << breadth ;
            cout << "\n Area = " << area ; 
        }
}; // End of the derived class definition
int main(void)
{
    Rectangle1 r1;
    r1.Enter_lb();
    r1.Rec_area();
    r1.Display();
    return 0;
}

Output:

Enter the length of the rectangle : 12.3
Enter the breadth of the rectangle : 13.2
Length = 12.3
Breadth = 13.2
Area = 162.36

Accessibility in Public inheritance

Accessibilityprivate variablesprotected variablespublic variables
Accessible from own class?YESYESYES
Accessible from derived class?NOYESYES
Accessible from 2nd derived class?NOYESYES

Private inheritance

When a derived class privately inherits a base class, all the public members of the base class become private for the derived class. In this case, the public members of the base class can only be accessed by the member functions of the derived class. 
The objects of the derived class cannot access the public members of the base class.

Note: that whether the derived class is inherited publicly or privately from the base class, the private members of the base class cannot be inherited.

/* This program has a base class Rectangle, from which class Rectangle1 is inherited publicly. */

#include <iostream>

using namespace std;

class Rectangle // Base class
{
    private:
        float length ; // This data member can't be inherited
    public:
        float breadth ; // This data member is inheritable
        void Enter_lb(void)
        {
            cout << "\n Enter the length of the rectangle: "; 
            cin >> length ;
            cout << "\n Enter the breadth of the rectangle: "; 
            cin >> breadth; 
        }
        float Enter_l(void)
        {
            return length;
        }
        void Display_l(void)
        {
            cout << "\n Length = " << length ;
        }
}; // End of the base class Rectangle.
/* 
    - Defining the derived class Rectangle1. 
    - This class has been derived from the base class i.e. Rectangle, privately.
*/

class Rectangle1 : private Rectangle 
{ 
    //All the public members of the base class Rectangle become private for the derived class Rectangle1.
    private:
        float area;
    public:
    void Rec_area(void)
    {
        Enter_lb();
        area = Enter_l() * breadth ; // length can't be used directly
    }
    void Display(void)
    {
        Display_l(); // Displays the value of length.
        cout << "\n Bredth = " << breadth;
        cout << "\n Area = " << area << endl;
    }
};
int main(void)
{
    Rectangle1 r1;
    r1.Rec_area() ; 
    // r.Enter_lb( ); will not work as it has become private for the derived class.
    r1.Display( ) ;
    // r.Display_l( ) will not work as it also has become private for the derived class.
    return 0;
}

Output:

Enter the length of the rectangle: 12.3
Enter the breadth of the rectangle: 14.3
Length = 12.3
Bredth = 14.3
Area = 175.89

Accessibility in Private inheritance

Accessibilityprivate variablesprotected variablespublic variables
Accessible from own class?YESYESYES
Accessible from derived class?NOYES(as a private member)YES(as a private member)
Accessible from 2nd derived class?NONOYES

Protected inheritance



The third access specifier provided by C++ is protected. The members declared as protected can be accessed by the member functions within their own class and any other class immediately derived from it.

These members cannot be accessed by the functions outside these two classes. Therefore, the objects of the derived class cannot access protected members of the base class.

When the protected members (data, functions) are inherited in public mode, they become protected in the derived class. Thus, they can be accessed by the member functions of the derived class. On the other hands, if the protected members are inherited in the private mode, the members also become private in the derived class. They can also be accessed by the member functions of the derived class, but cannot be inherited further. Overriding the member functions: The member functions can also be used in a derived class, with the same name as those in the base class. One might want to do this so that calls in the program work the same way for objects of both bases and derived classes.

The following program will illustrate this concept.

#include <iostream>

using namespace std;

const int len = 20;
class Employee
{
    private:
        char firstName[len];
        int idNumber;
        int age;
        float salary;
        public:
            void Enter_data(void)
            {
                cout << "\n Enter the first name = "; 
                cin >> firstName;
                cout << "\n Enter the identity number = " ; 
                cin >> idNumber;
                cout << "\n Enter the age = " ; 
                cin >> age;
                cout << "\n Enter the salary = " ; 
                cin >> salary ; 
            }
            void Display_data(void)
            {
                cout << "\n Name = " << firstName;
                cout << "\n Identity Number = " << idNumber;
                cout << "\n Age = " << age;
                cout << "\n Salary = " << salary;
            }
}; // End of the base class
class Engineer : public Employee
{
    private:
        char design[len] ; // S_Engineer, J_Engineer, Ex_Engineer etc
    public:
        void Enter_data()
        {
            Employee :: Enter_data() ; // Overriding of the member function
            cout << "\n Enter the designation of the Engineer: " ; 
            cin >> design ; 
        }
        void Display_data(void)
        {
            cout << "\n *******Displaying the particulars of the Engineer**** \n" ;
            Employee :: Display_data() ; // Overriding of the member function
            cout << "\n Designition = " << design;
        }
}; // End of the derived class
int main(void)
{
    Engineer er ;
    er.Enter_data();
    er.Display_data(); 
    return 0;
}

Accessibility in Protected inheritance

Accessibilityprivate variablesprotected variablespublic variables
Accessible from own class?YESYESYES
Accessible from derived class?NOYESYES(as a protected member)
Accessible from 2nd derived class?NOYESYES

whatsapp

error: Content is protected !!