Summary: In this tutorial, we will learn to implement single inheritance in C++.

Introduction to Single Inheritance

If a single subclass inherits a single base class, it is termed as single inheritance.

As the name suggests, single inheritance is nothing but inheritance involving only two classes.

Here is the block diagram, that illustrates the concept of single inheritance:

Block Diagram of Single Inheritance in C++

In this, we inherit the base class in the derive class to use its properties and functions.

Syntax for Single Inheritance:

class Base {
    //class members
};
 
class Derive : <access_specifier> Base {
    //class members
};

The mode of single inheritance varies depending on the type of access specified (public, private, or protected).

C++ Example: Single Inheritance

#include <iostream>
using namespace std;
 
class Account{
    double balance = 0.0;
public:
    double getBalance(){
        return this->balance;
    }
 
    void deposit(double amt){
        this->balance += amt;
        cout << amt <<" Deposited" << endl;
    }
    
    void withdraw(double amt){
        this->balance -= amt;
        cout << amt<<" Withdrawn \n";
    }
};
 
class SavingsAccount :public Account{
public:
    double interestRate;
 
    SavingsAccount(){
        interestRate = 5.1;
    }
 
};
 
int main()
{
   SavingsAccount sa;
   sa.deposit(1000);
   sa.withdraw(400);
 
   cout << "Savings Account Balance: "<< sa.getBalance() << endl;
}

Output:

Output of Single Inheritance Program

In this example, we inherited the Account class in the public mode, so all the public member methods of the Account class were accessible via the object of the SavingAccount.

In conclusion, single inheritance is the inheritance of a single class in a single subclass.

This Post Has One Comment

  1. Lynette

    Greeting of the day!

Leave a Reply

three × 2 =