0

I see this code. Is it valid to use : int area () {return (*width * *height);} after destructors?

// 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;//
}////

5 Answers5

1

In this code, you haven't "used" int area () {return (*width * *height);} after the destructors, you've only declared it after the destructors.

That is valid.

However, if you're asking if other code could call area after the object has been destroyed, it cannot.

1

Is it valid to use : int area () {return (*width * *height);} after destructors?

Actually you can not use the object that contains method area because it's destructed.

Example:

CRectangle *r = new CRectangle(100,200);
...
delete r;

r->area(); 
// There's no "r" anymore so it doesn't matter *width or *height are valid or not
// you can't access to "area" method
masoud
  • 55,379
  • 16
  • 141
  • 208
1

It is definitely invalid to use either of *height or *width after free. However, it is also invalid to use an object in general after it has been destroyed. Since the freeing of the pointers happen in the destructor, it is acceptable.

However, your code breaks the "rule of three": When a class allocates its own memory, it needs to have a copy constructor and an assignment operator, or you will either leak memory or get "use of memory that you shouldn't be using" (or both).

Consider:

...
CRectangle r1(10,25);
CRectangle r2(10,26);

CRectangle bigger(0,0);

if (r1.area() > r2.area())
   bigger = r1;
else
   bigger = r2;

{
   CRectangle r3(200, 300);
   r1 = r3;
}   // r3 is destroyed here.
cout << r1.area() << endl;   // Bang, using freed memory. 

In your copy constructor and assignment operator, you need to make the relevant free of the old data and allocate new, depending on what you are doing.

[Of course, it's a complete waste of memory space and time to do this for two integers - even the best memory allocation I know of will use five times more memory this way than just having two integers in the class.]

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

Yes, deferenceing a dangling pointer after you free it is undefined behaviour.

Vijay
  • 65,327
  • 90
  • 227
  • 319
0

Are you asking if it is legal to call area() on an object after you have destroyed the object?

No.

Never.

Why would you even think that you could, should or would!

John3136
  • 28,809
  • 4
  • 51
  • 69