Practice mode C++

Assuming standard headers and using namespace std, what does this C++ code print? struct A { virtual char n() const { return ‘A’; } }; struct B : A { char n() const override { return ‘B’; } }; void show(A a) { cout << a.n(); } int main() { B b; show(b); A& r = b; cout << r.n(); }

Correct answer C. AB

Explanation

show takes its parameter by value, so passing b copies only the A subobject into a brand new A: this is object slicing, and a.n() returns 'A'. The reference r, however, refers to the original B object, so the virtual call dispatches to B::n. Polymorphism only works through pointers or references, never through by-value copies.

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.