Skip to content
Related Articles

Related Articles

Improve Article

C++ | Destructors | Question 4

  • Last Updated : 28 Jun, 2021




#include <iostream>
using namespace std; 
class A
{
    int id;
    static int count;
public:
    A() {
        count++;
        id = count;
        cout << "constructor for id " << id << endl;
    }
    ~A() {
        cout << "destructor for id " << id << endl;
    }
};
   
int A::count = 0;
   
int main() {
    A a[3];
    return 0;
}

(A)

constructor for id 1
constructor for id 2
constructor for id 3
destructor for id 3
destructor for id 2
destructor for id 1

(B)

constructor for id 1
constructor for id 2
constructor for id 3
destructor for id 1
destructor for id 2
destructor for id 3

(C)

Compiler Dependent.

(D)

constructor for id 1
destructor for id 1


Answer: (A)

Explanation: In the above program, id is a static variable and it is incremented with every object creation. Object a[0] is created first, but the object a[2] is destroyed first. Objects are always destroyed in reverse order of their creation. The reason for reverse order is, an object created later may use the previously created object. For example, consider the following code snippet.

A a;
B b(a);

In the above code, the object ‘b’ (which is created after ‘a’), may use some members of ‘a’ internally. So destruction of ‘a’ before ‘b’ may create problems. Therefore, object ‘b’ must be destroyed before ‘a’.

Quiz of this Question

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.
My Personal Notes arrow_drop_up
Recommended Articles
Page :