Here’s the following code.
#include <iostream>
using namespace std;
class B {
private:
int a=1;
protected:
int b=2;
public:
int c=3;
};
class D : protected B { // clause 1
};
class D2 : public D { // clause 2
void x() {
c=2;
}
};
int main() {
D d;
D2 d2;
cout << d2.c; // clause 3 Error due to c being protected
return 0;
}
Note:
- Clause 1 would make c to be protected.
- Clause 2 would make c (protected in clause 1) to be public again.
- Why clause 3 failed?
>Solution :
The type of inheritance you use does not affect the protection level of members in the parent class. It only changes the protection level of those members in the child class.
When you define class D : protected B it is equivalent to defining class D like this:
class D
{
protected:
int b=2;
int c=3;
};
Then when you define class D2 : public D it is equivalent to defining class D2 like this:
class D2
{
protected:
int b=2;
int c=3;
};