C++ is an Object Oriented Programming Language (OOP) and Inheritance is one of the features of object-oriented programming which allow reusability of one class into another class.

What is Inheritance in C++?

To understand inheritance and its use, examine this situation.

An Account in a bank can be of different types, depending on the interest rate or deposit and withdrawal limit or any other factor.

Some examples are:

  • Savings Account
  • Current Account
  • Recurring Deposit Account

All the account has few things in common despite having different account types and features:

  1. Balance
  2. Deposit
  3. Withdraw

So if you are asked to create a class for each of the 3 accounts listed above and provide deposit and withdraw function for all account, What you will do?

If you don’t know inheritance than you must be thinking of creating three classes for each account type and write the deposit and withdraw function in each class.

Let me tell you it is useless to write the same code for deposit and withdraw for every class. Writing same code, again and again, is a great demerit in the programming world.

Here comes the inheritance in rescue.

With Inheritance, you only need to specify withdraw and deposit function for a single class (account), rest of the class will derive the deposit and withdraw functionality from that class.

It is possible because inheritance allows one class to extend to another class and thus implements reusability of classes.

Inheritance Example in C++


inheritance example in c++

The program has two class Account & SavingAccount. Both the account type/class has 3 things in common:

  1. Balance
  2. Deposit
  3. withdraw

Therefore in spite of writing same methods for SavingAccount class, with inheritance, we are using the methods of Account class.

inheritance in c++

SavingAccount class is extending to Account class i.e SavingAccount is deriving resource from Account class. That’s why we have not declared balance, deposit & withdraw in SavingAccount. Therefore

  • SavingAccount: is Derive Class
  • Account: is Base Class

By seeing the output we can say that SavingAccount class is using Account class resources. In short, SavingAccount inherits Account.

Types of Inheritance in C++

  1. Single Inheritance
  2. Multiple Inheritance
  3. Hierarchical Inheritance
  4. Multilevel Inheritance
  5. Hybrid Inheritance

Types of inheritance in C++

Hence we have successfully implemented inheritance in C++ using an example. If you have any doubts regarding inheritance than do comment below.


Leave a Reply