Prerequisite: Access modifiers in c, Inheritance
- What is the output?
#include <iostream>usingnamespacestd;classaccess{inta = 10;voiddisp(){cout<<"a: "<< a;}};intmain(){access a;a.disp();return0;}Output:
Error
Description: When the access specifiers are not specified then they are taken as private by default. The private variables can be accessed only with in the class and can not be accessed using . operator too if not public.
- What is the output?
#include <iostream>usingnamespacestd;classaccess{private:inta_pri = 10;protected:intb_pro = 20;public:intc_public = 30;};intmain(){access a;cout<<"private: "<< a.a_pri;cout<<"protected: "<< a.b_pro;cout<<"public: "<< a.c_public;return0;}Output:
error
Description: private and protected variables cannot be accessed out side the class.
- What is the output?
#include <iostream>usingnamespacestd;classaccess{protected:intb_pro = 20;public:intc_public = 30;};classaccess_modifier:publicaccess{public:voiddisp(){cout<<"protected: "<< b_pro << endl;cout<<"public: "<< c_public << endl;}};intmain(){access_modifier a;a.disp();return0;}Output:
protected: 20 public: 30
Description: protected variables can be accessed only in a derived from it.Here we cannot print a_pri as it is a private member and they cannot be accessed in the derived class irrespective of typpe of inhertance.
- What is the output?
#include <iostream>usingnamespacestd;classrectangle{intx, y;public:voidval (int,int);intarea (){return(x * y);}};voidrectangle::val (inta,intb){x = a;y = b;}intmain (){rectangle rect;rect.val (3, 4);cout <<"rect area: "<< rect.area();return0;}Output:
rect arera: 12
Description: since, both area() and val() are declared as public they can be accessed out side the class.
- What is the output?
#include <iostream>usingnamespacestd;classaccess{public:inta_public = 30;};classaccess_modifier:privateaccess{};classinheritance:publicaccess_modifier{public:voiddisp(){cout<< access::a_public;}};intmain(){inheritance a;a.disp();return0;}Output: error
Description: When a class is derived as private inheritance then it’s variables becomes private and are accessed only in that class and on further inhertance they are not accessible.
This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



