Reputation: 2087
According to: http://www.cplusplus.com/doc/tutorial/classes/
The destructor fulfills the opposite functionality of the constructor. It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using the operator delete.
Example code:
class Something
{
public:
Something() {cout << "construction called" << endl; }
~Something() { cout << "destruction called" << endl; }
};
void foo(){
Something *ob = new Something();
}
int _tmain(int argc, _TCHAR* argv[])
{
foo();
}
Upvotes: 0
Views: 14518
Reputation: 75130
The destructor is called before the object is destroyed. Since you allocated the object with new
, you must manually explicitly destroy it and deallocate the memory it occupied by calling delete
on a pointer to the object.
If you had created the object in automatic storage, à la
Something ob;
The object would be destroyed automatically and the destructor would be called as the object went out of scope when foo
returns.
Upvotes: 6
Reputation: 258548
That's true, but you allocate the object in dynamic memory, which means it won't be destructed until you call delete
.
because it is an object dynamically assigned and it is released using the operator delete.
You never call delete. Ergo memory leak and uncalled destructor:
void foo(){
Something *ob = new Something();
delete ob;
}
Either this, or simply allocate the object in automatic memory:
void foo(){
Something ob;
}
or delegate the memory management to a smart pointer.
Upvotes: 8