|
-
January 20th, 2011, 10:55 AM
#5
Re: Objects of a class
 Originally Posted by Learned
Can you please explain this?
Also if the object is created on stack why do we need destructor? In the main(), objects would behave as automatic variable and get destroyed automatically right before the scope of main ends. In the same manner as for any other function.
E.g.
Code:
void f()
{
double d;
}
The object d gets destroyed automatically when the scope of function is over.
The destructor is for the object to clean up any memory it may have used. In your simple example, you don't need one, but if the object contained a pointer to something it had allocated on the heap, it would need to delete that memory, and the destructor is the best place to do that.
The object getting deleted when it goes out of scope has nothing to do with whether you need a destructor or not. As Lindley said, the object itself may reside on the stack, but that doesn't mean it isn't allocating stuff on the heap.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|