C++ inheritance

C++ Inheritance




One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Base and Derived Classes

A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form −
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows −
#include <iostream>
 
using namespace std;

// Base class
class Shape {
   public:
      void setWidth(int w) {
         width = w;
      }
      void setHeight(int h) {
         height = h;
      }
      
   protected:
      int width;
      int height;
};

// Derived class
class Rectangle: public Shape {
   public:
      int getArea() { 
         return (width * height); 
      }
};

int main(void) {
   Rectangle Rect;
 
   Rect.setWidth(5);
   Rect.setHeight(7);

   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;

   return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35

Access Control and Inheritance

A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.
We can summarize the different access types according to - who can access them in the following way −
Accesspublicprotectedprivate
Same classyesyesyes
Derived classesyesyesno
Outside classesyesnono
A derived class inherits all base class methods with the following exceptions −
  • Constructors, destructors and copy constructors of the base class.
  • Overloaded operators of the base class.
  • The friend functions of the base class.

Modes of Inheritance

When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. The type of inheritance is specified by the access-specifier as explained above.
We hardly use protected or private inheritance, but publicinheritance is commonly used. While using different type of inheritance, following rules are applied −
  • Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
  • Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.
  • Private Inheritance − When deriving from a privatebase class, public and protected members of the base class become private members of the derived class.

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
    #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
    
    Please visit this link to learn multiple inheritance in details.
  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 implement
    // 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 for 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
Advantages of inheritance are as follows:
  • Inheritance promotes reusability. When a class inherits or derives another class, it can access all the functionality of inherited class.
  • Reusability enhanced reliability. The base class code will be already tested and debugged.
  • As the existing code is reused, it leads to less development and maintenance costs.
  • Inheritance makes the sub classes follow a standard interface.
  • Inheritance helps to reduce code redundancy and supports code extensibility.
  • Inheritance facilitates creation of class libraries.

Disadvantages of inheritance are as follows:
  • Inherited functions work slower than normal function as there is indirection.
  • Improper use of inheritance may lead to wrong solutions.
  • Often, data members in the base class are left unused which may lead to memory wastage.
  • Inheritance increases the coupling between base class and derived class. A change in base class will affect all the child classes.


Comments