Search code examples
c++inheritanceclass-visibility

Using late binding to call a private method from a non private context


I was surprised by the output produced by the piece of code below (g++ 4.4.7).

class A {
public:
    virtual void f() {std::cout << "A::f()" << std::endl;}
};

class B : public A {
private:
    // Automatically virtual, because of base class
    void f() {std::cout << "B::f()" << std::endl;}
};

int main(int argc, const char *argv[])
{
    A *pB = new B();
    pB->f();
    return 0;
}

The output is

B::f()

I know that because of late binding the compiler cannot issue an error here, but why can we call a private method from a non-private context?

What is the rationale?


Solution

  • n3376 11.5.1

    The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it.

    11.5.2

    Access is checked at the call point using the type of the expression used to denote the object for which the member function is called. The access of the member function in the class in which it was defined (D in the example above) is in general not known.