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?
CodePudding user response:
Your notes are not entirely correct:
private
inheritance makespublic
,protected
andprivate
members beprivate
in the derived classprotected
inheritances makespublic
andprotected
members beprotected
in the derived class, andprivate
members stayprivate
public
inheritance changes nothing to the derived members' access.
c
is protected
in D
and still protected
in D2
because of the public
inheritance. There is no way to cheat visibility. What you assume would break logic. Visibility only goes downwards, not up.
CodePudding user response:
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;
};