ProgrammingHardMicrosoft/Amazon SDE MCQ · GATE CS
What is printed?
What is printed?
struct P { const char* s; P(const char* s) : s(s) { cout << s; } ~P() { cout << "~" << s; } };
struct B { P b{"B"}; };
struct D : B {
P y, x;
D() : x("X"), y("Y") { }
};
int main() { D d; }- A. BXY~Y~X~B
- B. BYX~B~Y~X
- C. BYX~X~Y~B
- D. YXB~B~X~Y
Correct answer: C. BYX~X~Y~B
Bases are built first (B's member prints B), then members in DECLARATION order, y then x, whatever the initializer list says. Destruction is the exact reverse: ~X, ~Y, then the base's ~B.
More OOP with C++ and Java questions
- What is printed? cpp struct B { virtual ~B() { hi(); } virtual void hi() { cout << "B"; } }; struct D : B { ~D() { hi(); } void hi()…
- What is printed? cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }; struct D : B { void f(int x = 2) override { cout << "D"…
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { void f(double) { cout <<…
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { using B::f; void…
- What is printed? cpp struct B { virtual char id() const { return 'B'; } }; struct D : B { char id() const override { return 'D'; } }; void…
- What is printed when compiled as C++17? cpp struct T { T() { cout << "c"; } T(const T&) { cout << "k"; } }; T make() { return T(); } int…