< C++ Tutorial

C++ Inheritance

← Previous Next →


 

Inheritance is the capability of one class to acquire properties and characteristics from another class. The class whose properties are inherited by other class is called the Parent or Base or Super class. And, the class which inherits properties of other class is called Child or Derived or Sub class.

Inheritance makes the code reusable. When we inherit an existing class, all its methods and fields become available in the new class, hence code is reused.

NOTE : All members of a class except Private, are inherited


Purpose of Inheritance

  • Code Reusability
  • Method Overriding (Hence, Runtime Polymorphism.)
  • Use of Virtual Keyword

Basic Syntax of Inheritance


class Subclass_name : access_mode Superclass_name

While defining a subclass like this, the super class must be already defined or atleast declared before the subclass declaration.

Access Mode is used to specify, the mode in which the properties of superclass will be inherited into subclass, public, privtate or protected.

Example :

#include 
using namespace std;

class Adder{
   public:
      // constructor
      Adder(int i = 0) {
         total = i;
      }
		
      // interface to outside world
      void addNum(int number) {
         total += number;
      }
		
      // interface to outside world
      int getTotal() {
         return total;
      };
		
   private:
      // hidden data from outside world
      int total;
};

int main( ) {
   Adder a;
   
   a.addNum(10);
   a.addNum(20);
   a.addNum(30);

   cout << "Total " << a.getTotal() <<endl;
   return 0;
}

Types of Inheritance

In C++, we have 5 different types of Inheritance. Namely,

  • Single Inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Multilevel Inheritance
  • Hybrid Inheritance (also known as Virtual Inheritance)
← Previous Next →