Let us understand what does private inheritance mean…
Consider a simple example to illustrate the single inheritance. The 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#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 : private B //private derivation { private: int c; public: void mul(); void display(); }; |
In private derivation, the public members of the base class becomes private members of the derived class. Therefore, the objects of the derived class D cannot have direct access to the public member functions of the base class B.
Hence, if we create an object of the derived class D,
1 |
D x; |
The statements such as:
1 2 3 |
x.get_ab(); //get_ab() is private x.get_a(); //get_a() is private x.show_a(); //show_a() is private |
will not work. However, these functions can be used inside mul() and display() like the normal functions as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 |
void mul() { get_ab(); c = b * get_a(); } void display() { show_a(); //outputs value of a cout << "b = " << b << endl; cout << "c = " << c << endl; } |