Practice mode C++

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.

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.