Thursday, 21 September 2017

Derive class inheriting from private base class C++ program of single level inheritance

/*
Title: Derive class inheriting from private base class
 Derive class inherits all members of base class except constructor and destructor
 Even though private members are inherited but cant be accessed directly into derive class
*/

#include "iostream"
using namespace std;

class PrivateDemo{
 string name;
 public: 
  PrivateDemo(){
   name = "Pavan";
   cout<<"\nBase Constructor";
  }
  void setName(){
   cout<<"\nEnter Name: ";
   cin>>name;
   cout<<"\nYou have entered: "<<name<<endl;
  }

};

class Derive: private PrivateDemo{
 public:
  Derive(){
   cout<<"\nDerive constructor";
  }
  void deriveFun(){
   setName();
  }   

};

int main(){
 Derive ob;
 ob.deriveFun();
 return 0;
}
/*
 OUTPUT
[pavan@localhost Unit-2-Inheritance]$ g++ PrivateDemo.cpp
[pavan@localhost Unit-2-Inheritance]$ ./a.out 

Base Constructor
Derive constructor
Enter Name: Pavan

You have entered: Pavan
[pavan@localhost Unit-2-Inheritance]$ 

*/

No comments: