ProgrammingVery hardInfosys DSE · Wipro Elite

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)
struct A { virtual void p() { cout << "A"; } };
struct B : A { int z; void p() override { cout << "B"; } };
void f(A a) { a.p(); }
int main() { B b; f(b); A& r = b; r.p(); A c = b; c.p(); }
  1. A. BBB
  2. B. ABA
  3. C. AAA
  4. D. BAB

Correct answer: B. ABA

f(A a) and A c = b slice the object to a pure A, so A::p runs; only the reference r keeps the dynamic type B.

More OOP with C++ and Java questions

Exams that ask this topic