ProgrammingModerateMicrosoft/Amazon SDE MCQ · GATE CS
What is printed?
What is printed?
struct B { virtual char id() const { return 'B'; } };
struct D : B { char id() const override { return 'D'; } };
void byVal(B b) { cout << b.id(); }
void byRef(const B& b) { cout << b.id(); }
int main() {
D d;
byVal(d);
byRef(d);
B arr[1] = { d };
cout << arr[0].id();
}- A. DDD
- B. BDB
- C. BDD
- D. DDB
Correct answer: B. BDB
Passing by value and copying into a B array both slice the object to a plain B, so id() returns 'B'. Only the reference keeps the dynamic type D.
More OOP with C++ and Java questions
- What is printed when compiled as C++17? cpp struct T { T() { cout << "c"; } T(const T&) { cout << "k"; } }; T make() { return T(); } int…
- What is printed? cpp struct C { static int n; C() { ++n; } C(const C&) { ++n; } ~C() { --n; } }; int C::n = 0; void f(C c) { cout << C::n…
- What is printed? cpp struct N { int v; N& operator++() { v += 10; return this; } N operator++(int) { N t = this; v += 1; return t; } }…
- What is printed? cpp struct A { int x = 1; }; struct B : virtual A { B() { x += 10; } }; struct C : virtual A { C() { x += 100; } }…
- What is printed? cpp struct A { A(int v) { cout << v; } }; struct B : virtual A { B() : A(1) { } }; struct C : virtual A { C() : A(2) { }…
- What is printed? cpp struct V { V() { cout << 'V'; } }; struct X { X() { cout << 'X'; } }; struct M { M() { cout << 'm'; } }; struct D…