| Illustration of destructor activation when automatic variables go out of scope . | Lecture 3 - slide 9 : 36 Program 3 |
// When is the destructor called - and for which objects?
#include <iostream>
#include "point.h"
using namespace std;
int f(){
Point p, q, // The default constructor is used for both p and q
r(11.0, 12.0), // Point(double,double) used
s(p), // The copy constructor used
t(3.0), // Point(double) used
u = t, // Another way to use the copy constructor, via initializer
ap[10], // The default constructor used 10 times
*ps = new Point(1.0, 2.0); // A dynamically allocated point accessed by a pointer.
q = r; // default assignment - bit-wise copying, no use of copy constructor
cout << "Point p: " << p << endl; // (0,7)
cout << "Point q: " << q << endl; // (11,12)
cout << "Point r: " << r << endl; // (11,12)
cout << "Point s: " << s << endl; // (1,9)
cout << "Point t: " << t << endl; // (3,20)
cout << "Point u: " << u << endl; // (4,22)
for(int i = 0; i < 10; i++) // (0,7) ten times
cout << "ap[" << i <<
"]: " << ap[i] << endl;
cout << "*ps: " << *ps << endl; // (1,2)
// The Point destructor is called 16 times on exist from f.
// *ps is NOT destructed. delete ps destructs it.
}
int main(){
f();
}