Advertisement

C++ Question

Started by July 09, 2000 05:27 PM
19 comments, last by Esap1 24 years, 5 months ago
This is the point of destructors. When you delete an object, it''s destructor is called. The destructor for that object will then delete all the objects it contains, and it will go on until all the objects are deleted. For example:

class Foo
{
Foo();
~Foo();
char* myString;
}

class Bar
{
Bar();
~Bar();
Foo* myFoo;
}

// destructor for Foo..
CFoo::~CFoo ( )
{
if ( myString ) delete myString;
}

// destructor for Bar
CBar::~CBar ( )
{
if ( myFoo ) delete myFoo;
}

// in your program..
void main ( )
{
CBar* myBar = new CBar;
// do stuff..
// ...
// end of program, clean up time
delete myBar; // will result in everything being deleted
}


And that''s destructors, 101. By the way, if you aren''t using pointers, the destructors will still be called when the object goes out of scope. For example:

// we''ll just change the main function
void main ( )
{
CBar myBar;
// do stuff
// ...
// no clean up necessary, destructor will automatically
// be called for myBar when function ends
}

Because myBar is declared in the function, it will go out of scope at the end of function. Then the destructor for it will be called automatically, which will clean up all your memory. However, if you used a pointer to a CBar like in the first main function, and you allocated memory for it with new, it would NOT automatically go out of scope. You would have to use delete, like in the first main function.

Hope that clears everything up.

-RWarden (roberte@maui.net)

This topic is closed to new replies.

Advertisement