ProgrammingVery hardProduct company interview · GATE level

What happens with this code?

What happens with this code?
class B {
public:
    virtual void f() { cout << "B"; }
};
class D : public B {
private:
    void f() override { cout << "D"; }
};
int main() {
    D d;
    B& b = d;
    b.f();      // L1
    d.f();      // L2
}
  1. A. It compiles and prints BD
  2. B. L1 fails to compile because D::f is private
  3. C. It compiles and prints DD
  4. D. L2 fails to compile; with L2 removed the program prints D

Correct answer: D. L2 fails to compile; with L2 removed the program prints D

Access is checked at compile time against the static type used in the call. Through B&, f is public in B, so L1 compiles, and at run time virtual dispatch still reaches D::f even though D made it private: it prints D. Through d, the name f refers to D::f, which is private, so L2 is an error.

More OOP with C++ and Java questions

Exams that ask this topic