Access Control in C++ - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Access Control in C++

Share This

Here, we will discuss scope of the variables and functions declared in a base class and derived class. To illustrate this, let us take an example.

First, we deine a class A , which contains three variables having different visibility scope.

Then we define a subclass B which inherits the base class A using public scope.

We have commented the lines where variables are not accesssible.


#include <iostream> using namespace std; class A{ private: int a = 10; protected: int b = 20; public: int c = 30; void print(){ cout << a << endl; cout << b << endl; cout << c << endl; } }; class B : public A { private: int x = 11; protected: int y = 22; public: int z = 33; void print(){ //cout << a << endl; cout << b << endl; cout << c << endl; cout << x << endl; cout << y << endl; cout << z << endl; } }; int main(void){ A a; a.print(); B b; b.print(); //cout << a.a << endl; //cout << a.b << endl; cout << a.c << endl; //cout << b.a << endl; //cout << b.b << endl; cout << b.c << endl; //cout << b.x << endl; //cout << b.y << endl; cout << b.z << endl; return 0; }

If the class B inherits class A in protected mode, the variables and functions having public access in base class are inherited as protected members. Thus, accessibility change is shown in the follwing code.


#include <iostream> using namespace std; class A{ private: int a = 10; protected: int b = 20; public: int c = 30; void print(){ cout << a << endl; cout << b << endl; cout << c << endl; } }; class B : protected A { private: int x = 11; protected: int y = 22; public: int z = 33; void print(){ //cout << a << endl; cout << b << endl; cout << c << endl; cout << x << endl; cout << y << endl; cout << z << endl; } }; int main(void){ A a; a.print(); B b; b.print(); //cout << a.a << endl; //cout << a.b << endl; cout << a.c << endl; //cout << b.a << endl; //cout << b.b << endl; //cout << b.c << endl; //cout << b.x << endl; //cout << b.y << endl; cout << b.z << endl; return 0; }




Happy Exploring!

No comments:

Post a Comment