Access Control in C++ - BunksAllowed

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

Community

demo-image

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#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;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#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;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX




Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.