C++ Inheritance

C++ Inheritance is one of the powerful features of C++. As the name suggests inheritance is the technique of building new classes called derived classes from the existing class called a base class by inheriting the features of the base class.

C++ Inheritance: Introduction
Types of Inheritance
C++ Inheritance: Example

C++ programming inheritance

Apart from inheriting the properties of the base class, an extra new feature can be added to the derived class. A base class is called parental class and the derived class is called a descendant class as it inherits the feature of the parental class.

Look following picture for clear understanding.

C++ Inheritance

As shown in block diagram the derived class has inherited the feature X and Y of the base class and has its own feature A. So with inheritance new classes along with their own properties and the base class properties can be built. Apart from this inheritance also supports code re-usability. Re-usability in a simple sense means reusing the code that has been written and tested once. In above block diagram, while using features X and Y, the code doesn’t need to be written again. These can be used just by accessing.

Types of inheritance in C++

C++ Inheritance Syntax or Format

class base_class_name
class derived_class_name : acess_specifier base_class_name
} ;

In above syntax, access specifier is the access restriction imposed during the derivation of subclasses from the base class. It can be either private, protected or public.

C++ Inheritance Example

Here is a simple program to illustrate the concept of inheritance in C++.

// inheritance.cpp
#include <iostream>
using namespace std; 
class base
  int x;
  int y;
     x = 10;
     y = 15;
 class derive1 : public base   //public derivation
   void display()
      cout << "x of base class is not accessible" << endl;
      cout << "value of y in base class = " << y;
 int main()   //main program
   derive1 obj;
   return 0;
 }      //end of program


x of base class is not accessible
value of y in base class = 15


In the above program, class derive1 is a public derivation of the base class base. As a result, derive1 inherits all the public members of base. Hence, public members of the base class base is also a public memeber of the derived class derive1. The private memeber of base is not inherited by derived class derive1.