I found a similar code snippet. Let’s assume that there is a good reason to hide the virtual function in the derived class B. But this private member can be exposed via the base class as follows:
class A {
public:
virtual void print() const { std::cout << "hello A" << std::endl;}
};
class B: public A {
private:
void print() const override { std::cout << "hello B" << std::endl;}
};
int main() {
const A &a = B();
a.print(); // works unexpectedly (prints "hello B")
const B &b = B();
b.print(); // does not work (as expected)
}
Any idea why a.print() works, even though A should be dynamically bound to class B at runtime? Or does C++ ignore private/public classifier at runtime?
I executed the code above, didn’t expect a.print() to work since print() is private in the derived class.
>Solution :
Access control checks is by name, in the context of the static type of the expression it is used in. A::print is public, so a.print() is valid.
Virtual dispatch is unrelated to access control, so as a is bound to a B it calls B::print. If virtual dispatch considered access control, you would have to defer it to runtime to check, at least in some cases. E.g.
extern bool coinflip();
const A &a = coinflip() ? A{} : B{};
a.print();