I am just confused about the tiny program on inheritance below:
#include<iostream>
using namespace std;
struct B {
virtual int f() { return 1; }
}; // f is public in B
class D : public B {
int f() { return 2; }
}; // f is private in D
int main()
{
D d;
B& b = d;
cout<<b.f()<<endl; // OK: B::f() is public, D::f() is invoked even though it's private
cout<<d.f()<<endl; // error: D::f() is private
}
- I can't figure out why
D::f()is private,Dis public inherited fromB, so the public functionfinB
is also public inD(I know without inheritance, member access is private by default) fis a virtual function inB, so if we callb.f(), we actually callD::f(), but just as the illustration mentioned, whyD::f()is able to be invoked even though it's private?
Can anyone explain the simple inheritance problem in detail?
