In C++ Single inheritance, one base class is derived from one sub class. Hence the two related classes (Base & Sub class) exhibit one to one relation.
Syntax of Single Inheritance in C++
1 2 3 4 5 6 7 | class Base{ //Class Members }; class Derive : public Base { //Class Members }; |
Example for Single Inheritance in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <iostream> using namespace std; class Account{ public: double balance; Account(){ balance = 0.0; } void deposit(double amt){ balance += amt; cout << amt <<" Deposited" << endl; } //Pure Virtual Function void withdraw(double amt){ balance -= amt; cout << amt<<" Withdrawn \n"; } }; class SavingsAccount :public Account{ public: double interestRate; SavingsAccount(){ balance = 0.0; interestRate = 5.1; } }; int main() { SavingsAccount sa; sa.deposit(1000); sa.withdraw(400); cout << "Savings Account Balance: "<< sa.balance << endl; } |
Output
Single Inheritance is the simplest form of C++ Inheritance. The most important point to note is that only those members of the base class can be accessed in the derived class which is declared/specified as public. Private data members or members method cannot be accessed in the derived class (sub class).
Greeting of the day!