Simple Program for Single Inheritance Using C++ Programming

Inheritance is the most powerful feature of object-oriented programming. Inheritance is a form of software reusability in which new classes are created from existing classes by acquiring their attributes (data) and behaviors (functions). The existing classes are called as base/parent classes whereas the new classes are called as derived child classes.

The derived class not only inheritance all the capabilities of the base class but also can add new features & refinements of its own. By adding these refinements the base class remains unchanged.

In the Single Inheritance there will only one base class and only one derived class. The following is the schematic representation Class A is the base class and class B is the derived class. Only one class is derived from the base class. Have a look at the following example

Here, as you can see in the schematic representation, father is the base class and son is the derived class.

Single Inheritance

When we have a base class B and derived class D. Class B contains one private data member, one public data member, and three public member functions. Class D contains one private data member and two public member functions.

Simple Program for Single Inheritance Using C++ Programming

#include<iostream> using namespace std; class B{ int a; public: int b; void get_ab(){ cout<<"Enter Values for a and b :"; cin>>a>>b; } int get_a(){ return a; } void show_a(){ cout<<"\n a = "<<a; } }; class D : private B{ //class B is inherited in class D here int c; public: void mul(){ get_ab(); c = b * get_a(); } void display(){ show_a(); cout<<"\n b = "<<b; cout<<"\n c = "<<c; } }; int main(){ D d; d.mul(); d.display(); return 0; }


Enter Values for a and b : 10 20
a = 10
b = 20
c = 200

Explanation of the program

Here, we have first declared a base class called B and then derived a class called D from it. D inherits all the features of the base class B.