Assuming standard headers and using namespace std, what does this C++ code print? struct A { virtual void f() { cout << “A”; } void g() { cout << “a”; } }; struct B : A { void f() override { cout << “B”; } void g() { cout << “b”; } }; int main() { B b; A* p = &b; p->f(); p->g(); }
Correct answer B. Ba
Explanation
f is virtual, so the call through the base pointer is dispatched at run time to the dynamic type of the object, B, printing B. g is not virtual, so the call is bound at compile time using the static type of the pointer, A*, and A::g prints a. B::g merely hides A::g; it does not override it.
Answer checked How we write and check questions
Discussion