ProgrammingVery hardCognizant GenC · HCL

What is printed? (C++, assume <iostream> and using namespace std)

What is printed? (C++, assume <iostream> and using namespace std)
class B {
public:
    void call() { f(); }
private:
    virtual void f() { cout << "B"; }
};
class D : public B {
    void f() override { cout << "D"; }
};
int main() { D d; B& r = d; r.call(); }
  1. A. B
  2. B. BD
  3. C. Compile error because f is private
  4. D. D

Correct answer: D. D

Access control is checked at the call site (inside B, where f is accessible), while the virtual dispatch still selects D::f.

More OOP with C++ and Java questions

Exams that ask this topic