Summary: In this post, we will learn about inheritance in C++ with examples.

Introduction to Inheritance in C++

Inheritance is one of the properties of any object-oriented programming language.

It allows a class to reuse the properties of another class i.e. inheritance promotes code reusability.

The properties of the class include member variables and member functions.

Consider the following example.

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

Such types of bank account could be:

  • Savings Account
  • Current Account
  • Recurring Deposit Account

All the account types listed above has few things in common and some of them are:

  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 accounts, What you will do?

If you don’t know inheritance than you would end up creating three separate classes for each account type and write the deposit and withdraw function for each of them.

It is not efficient to write the same code for deposit and withdraw for every class.

Writing the same code, again and again, is a great demerit in the programming world. Here is why we use Inheritance.

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

It is possible because inheritance allows one class to reuse the code of another class.

Example of Inheritance in C++

Output

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 the 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