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?