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();
}- A. BDBDD
- B. DDBDD
- C. DDDDD
- 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
- What is printed? cpp struct M { M() { cout << "m"; } ~M() { cout << "~m"; } }; struct B { B() { cout << "b"; f(); } virtual ~B() { cout <<…
- What is printed? cpp struct P { P(const char s) { cout << s; } }; struct B1 { B1() { cout << "1"; } }; struct B2 { B2() { cout << "2"; }…
- What is printed? cpp struct A { A() { } A(const A&) { cout << "C"; } A& operator=(const A&) { cout << "="; return this; } }; void f(A a) {…
- What is printed? cpp struct B { virtual void f() = 0; }; void B::f() { cout << "B"; } struct D : B { void f() override { cout << "D"…
- What is printed? cpp struct C { static int n; C() { n++; } ~C() { n--; } }; int C::n = 0; void f(C c) { } int main() { C a; f(a); f(a); {…
- What is printed? cpp struct S { void f() { cout << "N"; } void f() const { cout << "C"; } }; void call(const S& s) { s.f(); } int main() {…