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.
Answer checked How we write and check questions
Discussion