Search⌘ K

- Examples

Learn how inheritance works in C++ by examining practical examples. Understand public, protected, and private access rights, abstract base classes with pure virtual methods, and how constructors are inherited. This lesson prepares you to apply inheritance principles effectively in your programs.

Example 1: Inheritance #

C++
#include <iostream>
class Account{
public:
Account(double b): balance(b){}
void deposit(double amt){
balance += amt;
}
void withdraw(double amt){
balance -= amt;
}
double getBalance() const {
return balance;
}
private:
double balance;
};
class BankAccount: public Account{
public:
// using Account::Account;
BankAccount(double b): Account(b){}
void addInterest(){
deposit( getBalance()*0.05 );
}
};
int main(){
std::cout << std::endl;
BankAccount bankAcc(100.0);
bankAcc.deposit(50.0);
bankAcc.deposit(25.15);
bankAcc.withdraw(30);
bankAcc.addInterest();
std::cout << "bankAcc.getBalance(): " << bankAcc.getBalance() << std::endl;
std::cout << std::endl;
}

Explanation #

  • We have created two classes, i.e., Account and BankAccount.

  • The BankAccount class inherits the Account class publicly in line 25.

  • The public member functions of the Account class are available to the BankAccount class and we can access them using the . ...