Single Inheritance – Public Inheritance in C++
Inheritance in which the derived class is derived from only one base class is called single inheritance.
Let us consider a simple example to illustrate the single inheritance. Program given below shows a base class B and a derived class D. The class B contains one private data member, one public data member and three public member functions. The class D contains one private data member and two public member functions.
#include<iostream.h> class B { private: int a; //private; not inheritable public: int b; //public; ready for inheritance void get_ab(); int get_a(); void show_a(); }; class D : public B //public derivation { private: int c; public: void mul(); void display(); }; /*...Defining of functions...*/ void B :: get_ab() { a = 5; b = 10; } int B :: get_a() { return a; } void B :: show_a() { cout << "a = " << a <<endl; } void D :: mul() { c = b * get_a(); } void D :: display() { cout << "a = " << get_a() << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; } /*...Main Program...*/ void main() { D x; x.get_ab(); x.mul(); x.show_a(); x.display() x.b = 20; x.mul(); x.display(); }
Given below is the output of the above program:
a = 5 a = 5 b = 10 c = 50 a = 5 b = 20 c = 100
In the above program, following things require to be noted:
- The class D is a public derivation of the base class B. Therefore, class D inherits all the public members of class B an retains their visibility. Thus, a public member of the base class B is also a public member of the derived class D
- The private members of the base class B cannot be inherited by the derived class D
- The class D, in effect, will have more members than what it contains at the time of declaration
- The program illustrates that the objects of class D have access to all the public members of class B
Let us have a look at the function show_a() and mul():
void B :: show_a() { cout << "a = " << a <<endl; } void D :: mul() { c = b * get_a(); }
Although the data member a is a private member of base class B and cannot be inherited, objects of derived class D are able to access it through an inherited member function of class B.
2 Responses
[…] Single Inheritance […]
[…] Single Inheritance […]