Let us consider a simple example to illustrate inheritance.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.





coding:





#include<iostream>

using namespace std;

class B

{

int a; //private:not in heritable

public:

int b;

void set_ab();

int getdata();

void show(void);

};

class D : public B

{

int c;

public:

void mul(void);

void display(void);

};





//---------------------





void B :: set_ab(void)

{

a=5;b=10;

}

int B :: getdata()

{

return a;

}

void B :: show()

{

cout<<"a:

"<<a;

}

void D :: mul()

{

c=b*getdata();

}

void D :: display()

{

cout<<"a="<<getdata()<<"

";

cout<<"b="<<b<<"

";

cout<<"c="<<c<<"



";

}

int main()

{

D d;

d.set_ab();

d.mul();

d.show();

d.display();

d.b=20;

d.mul();

d.display();

return 0;

}





outpost:





The class D is a public derivation of the base class B.Therefore,D inherits all the public members of B and retains their visibility.Thus,a public member of the base class B is also a public member of the derived class D.The private member of B cannot be inherited by D.The class D,in effect,will have more members than what it contains at the time of declaration as shown figure.





The program illustrates that the object of class D have access to all the public member of B .Let us have a look at the functions show() and mul():





void show()

{

cout<<"a="<<a<<"

";

}





void mul()

{

c=b*getdata();

}





Although the data member a is private in B and cannot be inherited,object of D are able to access it through an inherited member function of B.





class B

{

int a; //private:not in heritable

public:

int b;

void get_ab();

int getdata();

void show(void);

};

class D : public B

{

int c;

public:

void mul(void);

void display(void);

};





The membership of this derived class D is shown figure.In private derivation.the public members of the basic class become private members of the derived class.Therefore,the object of D cannot have direct access to the public member functions of B.





Adding more member to a class(by private derivation)





d.set_ab();

d.getdata();

d.show();





will not work.However,these functions can be used inside mul() and display() like the normal functions as shown below:





void mul()

{

set_ab();

c=b*getdata();

}

void display()

{

show(); //output value of `a`

cout<<"b="<<b<<"

";

cout<<"c="<<c<<"



";