ORDER IN WHICH OBJECTS ARE DESTROYED

Apr 28, 2008 at 4:53pm
class a{---------
---------};
int main(){
{a q,w,e;
}
}

doubt:in the above program object 'q' is created first then 'w' and later 'e' is created.
when cursor moves out of block in main in which 3 objects are created,destructor is called automatically and destroys objects in the reverse order in which they are created.that is 'e' is destroyed first then 'w' is destroyed and then 'q' is destroyed.
but how can we confirm that objects are destroyed in the reverse order in in which they are created??????
please write a program to confirm the above discussion.
Apr 28, 2008 at 6:43pm
Hint: Give each instance of the object (via constructor) a unique name, and output that name in the destructor for the object.
Apr 28, 2008 at 10:12pm
Yeah something like this should work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>
#include <iostream>
using namespace std;
class a
{
  private:
    a (void) {} //ensure that a constructor with no parameters cannot be used
    string _name;
  public:
    a (const char * x) { cerr << x << endl; _name = x; }
    a (string const& x) { cerr << x << endl; _name = x; }
    ~a (void) { cerr << '~' << _name << endl; }
};

int main (void)
{
  {
    a q("Q"), w("W"), e("E");
  }
}
Topic archived. No new replies allowed.