tags:

views:

361

answers:

2
#include<iostream>

using namespace std;
class base
{
public:
    virtual void add() {
        cout << "hi";
    }
};

class derived : public base
{
private:
    void add() {
        cout << "bye";
    }
public:
    void start() {
        cout << "start";
    }
};

int main()
{
    base *ptr;
    ptr = new derived;
    ptr->add(); 
    return 0;
}

Output is bye

I dont have a problem with how this is implemented. I understand you use vtables and the vtable of derived contains the address of the new add() function. But add() is private shouldn't compiler generate an error when I try to access it outside the class? Somehow it doesn't seem right.

+21  A: 

add() is only private in derived, but the static type you have is base* - thus the access restrictions of base apply.
In general you can't even know at compile time what the dynamic type of a pointer to base will be, it could e.g. change based on user input.

Georg Fritzsche
+1 - Thanks for the clarifying comment on my answer.
Kyle Rozendo
+4  A: 

To add a little to Georg's answer:

Remember that the compiler has no control over and cannot guarantee anything about derived classes. For example, I could ship my type in a library and derive from it in an entirely new program. How is the library compiler supposed to know that derived might have a different access specifier? The derived type didn't exist when the library was compiled.

In order to support this, the compiler would have to know access specifiers at runtime and throw an exception if you attempted to access a private member.

DeadMG