> In C++ you must always specifically call the destructor before the
> variable goes out of scope.  When it goes out of scope the variable name
> and the memory it points to become unlinked and there is no way for you to
> go back and free that memory.  That's how you get memory leaks :)

I think the above is a bit confusing. THe question was about calling the
destructor and then something about scope.

But talking about scope is confusing, since what you are talking about is
the pointers scope ... not the dynamically allocated object (would that
even make sense ... i.e. can you talk about the scope of a dynamic object
?)

Certainly memory leaks if an only pointer to some object goes out of scope
... but in many cases this doesn't matter since some other pointer will be
passed the address of the object in question.

Anyway, as Suresh pointed out, when a dynamic object is deleted it's
destructor is implicitly called.

To sum up the ways objects are destroyed:

1 When a dynamic object is deleted, the destructor is called IMPLICITLY

2 An automatic object (on the stack AFAIK) or static object will be
destroyed automatically, when it goes out of scope - i.e. at the end of a
block or at program termination, and then the destructor is called
IMPLICITLY.

The example below should serve as illustration. Three objects are created
in different ways. All are destroyed, but none explicitly. Actually, you
only rarely call the destructor EXPLICITLY, but take a look at:
 
http://www.cerfnet.com/~mpcline/C++-FAQs-Lite/

-------------------------
#include <iostream.h>

class foo 
{ 
        int x;  

public: 
        foo(int _x):x(_x) {}
        ~foo() { cout << "I am destroyed: " << x <<endl; } 
}; 

foo z(1);  

main()  
{
        foo * x = new foo(2); 
        delete x; 
        foo y(3);  
}
 ------- 
I am destroyed: 2 
I am destroyed: 3 
I am destroyed: 1






Reply via email to