Assuming standard headers and using namespace std, what does this C++ code print? struct A { A() { f(); } virtual void f() { cout << “A”; } }; struct B : A { void f() override { cout << “B”; } }; int main() { B b; b.f(); }
Correct answer B. AB
Explanation
While the A constructor is running, the B part of the object has not been constructed yet, so the object behaves as an A and a virtual call resolves to A::f, printing A. After construction finishes, b.f() calls B::f and prints B. Calling virtual functions from constructors or destructors never dispatches to more-derived overrides.
Answer checked How we write and check questions
Discussion