Possible duplicate:Why is it allowed to call a private virtual method of a derived class using a base class pointer?
I recently met a strange question, plz refers to the following code:
#include <iostream> using namespace std; class A { public: virtual void disp() { cout<<"A disp"<<endl; } }; class B : public A { private: void disp() { cout<<"B disp"<<endl; } }; int main() { A a; a.disp(); A *b = new B(); b->disp(); }
and output:
A disp B disp
I am wondering why the b pointer can access disp ()? This is personal! Is not it?
disp () is publicly available since you call it via A * and disp () is declared as public in A. Since it is virtual, the B version of disp is called, but this does not affect the publication or private.
This is for language design. However, it is bad practice to strengthen the level of protection of methods when receiving