ProgrammingVery hardWipro Elite · TCS NQT Prime

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

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)
struct A { virtual void f() { cout << "A"; } };
struct B : A {
private:
    void f() override { cout << "B"; }
};
int main() { A* p = new B; p->f(); }
  1. A. A
  2. B. Compile error: B::f is private
  3. C. Undefined behaviour
  4. D. B

Correct answer: D. B

Access is checked against the static type A*, where f is public; dispatch then reaches the private override B::f.

More OOP with C++ and Java questions

Exams that ask this topic