Inheritance in C++

  • The mechanism of deriving a class from another class is known as Inheritance.
  • Inheritance is the most importance concept of object oriented programming.
  • It allows us to define a class in terms of another class, which helps to create and maintain an application.
  • The main advantage of Inheritance is, it provides an opportunity to reuse the code functionality and fast implementation time.
  • The members of the class can be Public, Private or Protected.
    Syntax:
    class DerivedClass : AccessSpecifier BaseClass
  • The default access specifier is Private.
  • Inheritance helps user to create a new class (derived class) from a existing class (base class).
  • Derived class inherits all the features from a Base class including additional feature of its own.
Access Control

AccessibilityPrivatePublicProtected
From own classYesYesYes
From derived classNoYesYes
Outside derived classNoYesNo

Example: Program demonstrating implementation of Inheritance

#include <iostream>
using namespace std;
class Shape
{
   protected:
        float width, height;
   public:
        void set_data (float w, float h)
        {
                width = w;
                height = h;
        }
};
class Rectangle: public Shape
{
    public:
          float area ()
          {
                   return (width * height);
          }
};
class Triangle: public Shape
{
    public:
        float area ()
        {
                   return (width * height / 2);
        }
};
int main ()
{
        Rectangle r;
        Triangle t;
        r.set_data (4,4);
        t.set_data (3,7);
        cout << "Area of Rectangle : "<<r.area() << endl;
        cout << "Area of Triangle : "<<t.area() << endl;
        return 0;
}


Output:
Area of Rectangle: 16
Area of Triangle: 10.5

In the above example, class Shape is a base class and classes Rectangle and Triangle are the derived class. The derived class appears with the declaration of class followed by a colon(:), access specifier public and the name of the base class from which it is derived.

The Rectangle and Triangle are derived from Shape class, all the data members and member functions of the base class Shape can be accessible from derived class.