Practice mode C++

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.