When are constructors and destructors called?

It may be useful to understand when a basic constructor, a copy constructor, an intializing constructor or a destructor is called.

Suppose we have a class called Box which has a basic constructor, an initializing constructor, a copy constructor and destructor.

Here are some general guidelines:


Here is an example:

     Box F(Box, Box &);              // Line 1

     int main()                      // Line 2
     {                               // Line 3
      Box A;                         // Line 4
      Box B;                         // Line 5
      Box * C;                       // Line 6
      Box * D;                       // Line 7
      A = SomeValue;                 // Line 8
      B = A;                         // Line 9
      C = new Box(SomeValue);        // Line 10
      D = new Box(A);                // Line 11
      // various code, irrelevant    // Line 12
      D = C;                         // Line 13
      // irrelevant code             // Line 14
      if (true)                      // Line 15 
       {                             // Line 16
        Box E;                       // Line 17
        E = SomeOtherValue;          // Line 18
        B = F(*C, A);                // Line 19
        // more irrelevant code      // Line 20
        delete D;                    // Line 21
       }                             // Line 22
      return 0;                      // Line 23
     }                               // Line 24
                                               
     Box F(Box Arg1, Box & Arg2)     // Line 25
      {                              // Line 26
       Box T = Arg2;                 // Line 27
       // lots of irrelevant code    // Line 28
       return T;                     // Line 29
      }                              // Line 30

Let's go through this a line at a time.

The above list is not guaranteed to be complete. For instance, when is the temporary value returned by F going to be destroyed? Is it destroyed after line 19, after line 22 or after line 24?

Likewise, the program ends without deleting all the instances of Box which were created dynamically. These presumably disappear after line 24 when cleanup work is done.