Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does this work in C++? exposing private virtual member of a derived class through base class

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading