Possible Duplicate:
Why is it allowed to call derived class' private virtual method via pointer of base class?
Recently, I met a strange question, plz refer to 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 the output is:
A disp
B disp
I'm wondering why pointer b can access disp()? It's private! Isn't it?
disp() is public since you're calling it through an A* and disp() is declared as public in A. Since it is virtual, B's version of disp gets called, but that doesn't affect whether it's public or private.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With