constructor-destructor

This following code comes from the tutorial, Classes (I) chapter. It calls the constructor function for the CRectangle class which provides two values pointed by width & height, then calls the destructor and then calls the area function which needs the values pointed by width & height. How can it work if width & height are deleted before area is called ??

// example on constructors and destructors
#include <iostream>
using namespace std;

class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};

CRectangle::CRectangle (int a, int b) {
width = new int;
height = new int;
*width = a;
*height = b;
}

CRectangle::~CRectangle () {
delete width;
delete height;
}

int main () {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
The first 7 lines above just declare the class and its member functions.

The next 6 lines just provide the implementation of the constructor.

The next 4 lines just provide the implementation of the destructor.

Then last 6 lines -- main() -- do all the work.
The first line declares two CRectangles, named rect and rectb.
The next two lines print out the area of those two rectangles.
The last line causes main() to return, which automatically calls the destructors for both rect and rectb.

So area() is never called on a destroyed CRectangle object.
Ok, now I understand the fact that the first 7 lines are just a declaration, nothing is happening there.

But I thought that the point of destroying the dynamic memory allocation was to free some memory for the rest of the program to run better if it needs this memory, so why is this destructor only called at the very end of the program and not before ??

Thank you for your help anyway.
Your variables rect and rectb are only destroyed at the end of the program, when they go out of scope.

The destructor only gets called when the object is destroyed. So, given
1
2
3
4
5
6
7
8
9
int main() {
  CRectangle recta(3,4);
  {
    CRectangle rectb(5,6);
    cout << "The area of the rectangle with sides 5 and 6 is " << rectb.area() << endl;
  }
  cout << "The area of the rectangle with sides 3 and 4 is " << recta.area() << endl;
  return 0;
}

Line 1: program entry point
Line 2: recta is constructed
Line 3: new local block (scope)
Line 4: rectb is constructed
Line 5: rectb is used
Line 6: rectb is destructed
Line 7: recta is used
Lines 8 and 9: recta is destructed and program terminates

Hope this helps.
Yes I got it, thank you !!
Topic archived. No new replies allowed.