ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct B { virtual string who() const { return "B"; } };
struct D : B { string who() const override { return "D"; } };
void byVal(B b)        { cout << b.who(); }
void byRef(const B& b) { cout << b.who(); }
int main() {
    D d;
    B b = d;
    B* p = &d;
    byVal(d);
    byRef(d);
    cout << b.who() << p->who();
    vector<B> v{d};
    cout << v[0].who();
}
  1. A. BDBDD
  2. B. DDBDD
  3. C. DDDDD
  4. D. BDBDB

Correct answer: D. BDBDB

Copying a D into a B object slices it: only the B part is copied and the object's dynamic type is B, so virtual calls on it run B::who. That happens for the by-value parameter, for b = d, and for the vector element (a vector<B> stores B objects). Only the reference parameter and the pointer still refer to the D object, giving D. Output: B D B D B.

More OOP with C++ and Java questions

Exams that ask this topic