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; }
  1. A. BM1M2Ddm2m1b
  2. B. BM2M1Ddm1m2b
  3. C. M2M1BDdbm1m2
  4. 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

Exams that ask this topic