Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why I can access private method from outside in C++? [duplicate]

Tags:

c++

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?

like image 523
user1603164 Avatar asked Aug 16 '12 12:08

user1603164


1 Answers

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.

like image 117
Dirk Holsopple Avatar answered Sep 28 '22 10:09

Dirk Holsopple