From C ++ Primer 5th edition (D inherits from B)
Member functions and friends of classes derived from D can use the tobase derivative transformation if D inherits from B, using either open or protected. such code cannot use conversion if D inherits privately from B.
Is there any reason for this or should I take it at face value? It may seem obvious why this happens, but it turns me off in one example:
#include <iostream>
using namespace std;
class Base {
public:
int x = 2;
};
class Derived : protected Base { };
class DerivedAgain : public Derived {
friend void test();
};
void test() {
??? a;
Base* p = &a;
cout << p->x;
}
int main(){
test();
}
I want to understand test()
member accessibility x
in base-based transformations. Considering three potential cases of type ???
of a
in function test()
.
???
- Base
. x
is a public member Base
. In this case there is no problem.???
- DerivedAgain
. Derived-to-Base , test()
friend
DerivedAgain
, , Base
. x
.???
- Derived
. . ? . test()
Derived
, p->x
, , Derived-to-Base ? , ?
, test()
void test() {
Derived a;
cout << a.x;
}
, , x
, Derived
, protected
, , .
a
Base
DerivedAgain
, test()
, .
, , .