2.1.1 What is it?
Listing 1 is an example of protected inheritance.
1class A
2{ 3 int i;
4 protected:
5 int j;
6 public:
7 int k;
8};
9 10class B :
protected A
11{ 12 public:
13 int L;
14};
15 16class C :
public B
17{ 18};
19 20void test(
void)
21{ 22 B myB;
23 24 myB.i = 0;
25 myB.j = 0;
26 myB.k = 0;
27}
In this inheritance hierarchy, class B acts as a “gate” to limit the exposure of members from class A to class C. In this
particular example:
- Neither B or C can see A::i because it is private to A.
- B can see A::j and A::k because B inherits directly from A. However, both A::j and A::k are now limited as
protected.
- C can also see A::j and A::k because they are protected as exposed by class B.
- test(void) cannot see A::i, A::j or A::k. The first one is private, and the other two are protected in B.