C++ : Inheritance in private mode

 Single Inheritance in private mode


At the time of defining derived class after colon (:) if we write just base class name it means visibility specifier is public. It is not mandatory to write public keyword.  In public visibility specifier all members (Inheritable members) of BASE class will be copied into the public section of derived class. This is present in above example. what if we write private keyword instead of public keyword? Then all members of BASE class will be inherited into the private section of derived class. 



For Example:


#include<iostream>

class Student //BASE class

{

  private:

int rno;

  public:

void readstudent(int);

void printstudent(void);

};


void Student::readstudent(int r)

{

rno=r;

}


void Student :: printstudent(void)

{

cout<<"\nRno="<<rno;

}


class Test : private Student 

{

   private: int subject1, subject2;


   public:

void readtest(int,int);

void printtest(void);

};


void Test:: readtest(int x,int y,int z)

{

 

readstudent(x); //Calling base class function because of private mode inheritance  

 subject1=y;

 subject2=z;

}

void Test::printtest(void)

{

printstudent();  //Calling base class function because of private mode inheritance  

cout<<"\nSubject1 = "<<subject1

<<"\nSubject2="<<subject2;

}


main()

{

 Test t1; //Derived class object accessing both class functions

// t1.readstudent(); Error if we write

 t1.readtest(101,86,97);

// t1.printstudent(); Error if we write

 t1.printtest();

}


Comments