3

I have five user defined objects in my main as follows:

Is there any particular order in which their destructors get called? Like say the order of definition is as follows:

Student s1;
Student s2;
Student s3;
Student s4;
Student s5;

Does s5's destructor get called first or s1's?

Tim Southee
  • 51
  • 2
  • 6

2 Answers2

7

The destructors will be called in the order s5, s4, s3, s2, s1. This is a general rule: if two objects' lifetimes overlap, then the first to be constructed will be the last to be automatically destroyed. This, of course, does not apply to objects of dynamic storage duration, which are not destroyed automatically. (e.g., objects created with new are destroyed when you call delete.)

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Brian, I love you man. Thanks. – Tim Southee Apr 21 '15 at 05:19
  • You know, the funny thing is, when someone with as many points as Brian answers a question, you F'n know it's the right answer and take it for granted. Awesome! :) – Tim Southee Apr 21 '15 at 05:21
  • @TimSouthee Thanks, but I do make plenty of mistakes too :) – Brian Bi Apr 21 '15 at 05:22
  • What if s1, s2, s3, s4 and s5 are the data members of some other class called `College` and they are declared in that order (s1 first, s5 last) what is the order of destructor calls then? – Tim Southee Apr 21 '15 at 05:23
  • @TimSouthee, Everybody makes mistakes, definitely myself included. Anyway, the rule holds and it's still the opposite of construction, which is the order of declaration in the class in that case. – chris Apr 21 '15 at 05:24
  • @chris: I know, but having legends like you answer gives us a sense of security that we need not cross-check for validity. You guys really rock. – Tim Southee Apr 21 '15 at 05:29
3

Yes , the order of destruction is always opposite to the order of construction.

Please Look at the following code .

  class Base
  {
   public:

   Base ( )
   {
     cout << "Inside Base constructor" << endl;
   } 


  ~Base ( )
  {
    cout << "Inside Base destructor" << endl;
  } 

};

class Derived : public Base
{

 public:

 Derived  ( )
 {
   cout << "Inside Derived constructor" << endl;
 } 

 ~Derived ( )
 {
  cout << "Inside Derived destructor" << endl;
 } 

 };

  void main( )
  {
    Derived x;
  }

If you run this code you will get following output.

   Inside Base constructor
   Inside Derived constructor
   Inside Derived destructor
   Inside Base destructor
Kuldeep More
  • 138
  • 3
  • 14