ProgrammingVery hardProduct-company placement · GATE CS
What is printed?
What is printed?
struct M {
int id;
M(int i) : id(i) { cout << "M" << id; }
~M() { cout << "m" << id; }
};
struct B { B() { cout << "B"; } ~B() { cout << "b"; } };
struct D : B {
M m2;
M m1;
D() : m1(1), m2(2) { cout << "D"; }
~D() { cout << "d"; }
};
int main() { D d; }- A. BM1M2Ddm2m1b
- B. BM2M1Ddm1m2b
- C. M2M1BDdbm1m2
- D. BM2M1Ddm2m1b
Correct answer: B. BM2M1Ddm1m2b
Bases are built first, then members in DECLARATION order (m2, m1), whatever order the initialiser list uses, then the constructor body. Destruction is the exact reverse: d, m1, m2, b.
More OOP with C++ and Java questions
- 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 (C++17)? cpp int a[] = {1, 2, 3, 4}; int p = a + 1; cout << p++; cout << ++p; cout << p[-1];
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(const char) { cout << "Bs"; } }; struct D1 : B { void f(double) {…
- Which lines fail to compile? cpp struct B { void f() { } }; class D1 : B { }; struct D2 : B { }; class D3 : public B { }; int main() { D1…
- What is printed? cpp template <class T> void f(T) { cout << "T"; } template <class T> void f(T) { cout << "P"; } void f(int) { cout <<…
- What is printed? cpp struct S { void f() { cout << "N"; } void f() const { cout << "C"; } }; int main() { S a; const S b{}; const S& r =…