C++ Inheritance

Inheritance is probably the most powerful feature of object-oriented programming, after classes themselves. Inheritance is the process of creating new classes, called derived classes, from existing or base classes. The derived class inherits all the capabilities of the base class. So, in short, Inheritance is the process by which objects of one class acquire the properties of objects of another class in the hierarchy manner.

Advantage of Inheritance in C++

  • Reusability: It helps the code to be reused in the derived class. The base class is defined and once it is compiled, it needs not to be reworked.
  • Transitivity: If class B inherits properties of another class A, then all subclasses of class B will automatically inherit the properties of A. It is called transitive property.

Base & Derived Classes

One of the most powerful features of C++ is the use of inheritance to derive one class from another. Inheritance is the process by which a new class known as a derived class is created from another class, called the base class. A derived class automatically has all the member variables and functions that the base class has, and can have additional member functions and/or additional member variables.

Syntax:

Access specifiers/Visibility modes in Inheritance

There are three types of Access specifiers:

  • Public: When deriving a class from a public base class. Then the public members of the base class become public members of the derived class.
  • Protected: When deriving from a private base class. Then both public member and protected members of the base class will become Private in the derived class.
  • Private: When deriving from a protected base class. Then both public member and protected members of the base class will become protected in the derived class.

Single inheritance

It is defined as when one class inherits another class. In short only one parent/base class per derived class.

Example:

Multiple inheritance

Multiple Inheritance is the ability of a class to have more than one base class/ parent class.

Example:

Multiple inheritance

Multiple Inheritance is the ability of a class to have more than one base class/ parent class.

Example:

Hierarchical inheritance

It is defined as when many subclasses inherit from a single class, it is known as hierarchical inheritance.

Example:

Hybrid Inheritance

It is a combination of various types of inheritance can be combined in a program. This type of inheritance is called hybrid inheritance

Example: