Inheritance in C++

In this tutorial, we will learn about the inheritance in C++, its important and use with detailed example.

Definition:
Acquiring the properties of parent class to sub class objects is called Inheritance”


Concept of Inheritance

Base Classes and Derived Classes

In above diagram,  Car is Base class where as  pickup truck and truck class is dervied class. Inhertance allows to construct new classes by inheriting property of exixting class. In this process the new derived class inherits the data and methods of base class.

Pickup Truck object is a special kind of car it has all the feature of a car and additionally it has its own unique feature and same with the truck.


Types of inheritance in C++

  1. single inheritance
  2. multilevel inheritance
  3. hierarchical inheritance
  4. multiple inheritance
  5. hybrid inheritance

C++ Inheritance Syntax or Format

class base_class_name
{
   ..................
};
class derived_class_name : acess_specifier base_class_name
{
   ...........
} ;

Access specifier

The PublicProtected and Private keywords are the visibility labels in C++.

enter image description here

If no modifier then it isprivate by default.


Importance of inheritance

There are many benefits of using inheritance in software development.

Data Abstraction

General properties can be defined in base class and only special properties can be organized in a relationship using derived classes. All the features of car will be in base class Car and for the special properties of pickup truck, it will be defined in the pickup truck itself.

Re-usability

Class that are already defined and tested can be reused for performing new task.


Implementation of Inheritance in C++

class A  
{ 
public: 
    int x; 
protected: 
    int y; 
private: 
    int z; 
}; 
  
class B : public A 
{ 
    // x is public 
    // y is protected 
    // z is not accessible from B 
}; 
  
class C : protected A 
{ 
    // x is protected 
    // y is protected 
    // z is not accessible from C 
}; 
  
class D : private A    // 'private' is default for classes 
{ 
    // x is private 
    // y is private 
    // z is not accessible from D 
};