



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
An example of inheritance in c++ with different access specifiers (private, protected, public) for base class members. The example demonstrates how derived class objects can access base class members based on their access specifiers. The code includes constructors, destructors, and display functions.
Typology: Exercises
1 / 5
This page cannot be seen from the preview
Don't miss anything!
#include
//Base Class data overridden in Inherited cout<<"Private Member of Inhr_Base: "<<priv_baseInt<<endl; cout<<"Protected Member of Inhr_Base: "<<prot_baseInt<<endl; cout<<"Public Member of Inhr_Base: "<<publ_baseInt<<endl; //Base Class data //cout<<"Private Member of Base: "<<baseClass::priv_baseInt<<endl; //Inaccessible cout<<"Protected Member of Base: "<<baseClass::prot_baseInt<<endl; cout<<"Public Member of Base: "<<baseClass::publ_baseInt<<endl; } void display_Inherited() { //Inherited Class own function display_Vars(); //Base Class function baseClass::display_Vars(); } }; class privateGChild:private pubInherited { public: privateGChild() { cout<<"I am a Test class, privately Inherited from pubInherited"<<endl; cout<<"I can access (in my Class) : "<<endl; //Inherited Class Data //cout<<"Private Member of Inherited: "<<priv_InhrInt<<endl; //Inaccessible cout<<"Protected Member of Inherited: "<<prot_InhrInt<<endl; cout<<"Public Member of Inherited: "<<publ_InhrInt<<endl; } ~privateGChild() { cout<<"destructed โ> privateGChild"<<endl; } }; class GGChild_of_Private:public privateGChild { public: GGChild_of_Private() { cout<<"I am a Test class, inherited from a privately Inherited class"<<endl <<"Just to check the private access specifier"<<endl; cout<<"I cant access any thing"<<endl; //Inherited Class Data //cout<<"Private Member of Inherited: "<<priv_InhrInt<<endl; //Inaccessible //cout<<"Protected Member of Inherited: "<<prot_InhrInt<<endl; //Inaccessible //cout<<"Public Member of Inherited: "<<publ_InhrInt<<endl; //Inaccessible } ~GGChild_of_Private() { cout<<"destructed โ> GGChild_of_Private"<<endl; } };
privateGChild Object 1 ; //I (an Object) can't DIRECTLY access the public data of my base //as it has become private, neither my derived will //be abble to access it //Object 1 .display_Inherited(); protectedGChild Object 2 ; //I (an Object) can't DIRECTLY access the public data of my base //as it has become protected, neither my derived will //be abble to access it //Object 2 .display_Inherited(); }