Deconstructors

I had a question about when exactly deconstructors are processed in a program.

The example from this websites tutorial which I am looking at is on the bottom of the post.

I'm assuming that the deconstructor is called at the end of this constructor

1
2
3
4
5
6
CRectangle::CRectangle (int a, int b) {
  width = new int;
  height = new int;
  *width = a;
  *height = b;
} <<<< deconstructor is automatically checked for and called here?


Is that a correct assumption?


Full code listed here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 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;
}
Last edited on
A destructor (not deconstructor), is called when an object is destroyed, either through a delete call or by going out of scope. For example, rect/rectb inside your main function are destroyed when main returns.
thank you for the answer :)
Topic archived. No new replies allowed.