I've tried running the following piece of code. Notice that the function "g" calls the function "f" which is public in X but private in Y.
class X{
public:
virtual void f(void){cout<<"From X\n";}
virtual void g(X* x) { x->f();}
};
class Y: protected X{
private:
void f(void){cout<<"From Y\n";}
};
int main() {
Y y = Y();
Y *py = &y;
X* px = py;
py->g(py);
return 0;
}
The output is (Notice the inheritance is protected):
prog.cpp: In function ‘int main()’:
prog.cpp:18:10: error: ‘X’ is an inaccessible base of ‘Y’
X* px = py;
^
prog.cpp:7:16: error: ‘virtual void X::g(X*)’ is inaccessible
virtual void g(X* x) { x->f();}
^
prog.cpp:19:10: error: within this context
py->g(py);
^
prog.cpp:19:10: error: ‘X’ is not an accessible base of ‘Y’
prog.cpp:19:10: error: ‘X’ is an inaccessible base of ‘Y’
prog.cpp:18:5: warning: unused variable ‘px’ [-Wunused-variable]
X* px = py;
If I change the inheritance from protected to public then the code works and I get the following output:
From Y
It seems to me as if the private access restriction of wasn't enforced on the call to function "f" when the inheritance was public (Since Y::f was called from X). Before running this piece of code I thought I should always get a compile time error because of the access restriction (which was proved wrong).
Somehow changing the inheritance from public to protected fixes this and doesn't enable the call to Y::f. Can anyone explain why?