Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ destructors

Started by Pipo DeClown Jan 5, 2003 at 9:53 AM 9 replies 250+ views
Original Post
Pipo DeClown
Pipo DeClown
Does C++ destroy instances in the opposite order? Construction: class cClass { public: cClass2 Class2; sStruct* LinkedList; int numberofstructsinlist; cClass(); ~cClass(); }; So the Destruction: Every sStruct beginnin at the tail, ending at the head. Then the cClass2 Then the cClass. Am I correct? Report to moderator .lick
civguy
civguy
Not quite so.

First cClass destructor, then cClass2 destructor. And your sStruct* won''t be destroyed at all unless you destroy it in cClass destructor.

But the order is opposite to construction. cClass2 is constructed first, then cClass.
civguy
civguy
It doesn''t matter whether it has a destructor or not, if it isn''t called anywhere. It can be called explicitely, or usually through "delete LinkedList;"
Pipo DeClown
Pipo DeClown
hmm...

say if the I allocated memory for them though runtime...
the destructors should be called right?

~sStruct()
{
// safety checks
delete Next;
}

~cClass()
{
// safety checks
delete LinkedList;
}

~cClass2()
{
}

......

destruct order would be:
~tail();
~between();
~head();
~class2();
~class();


TRUE?!!!!!


.lick
civguy
civguy
You can try it out easily. Just put some "cout"s in the destructors.
SabreMan
SabreMan
quote:
Original post by Pipo DeClown
Does C++ destroy instances in the opposite order?

For objects which go on the stack, yes. That''s a property of a stack: last-in first-out.
quote:

Every sStruct beginnin at the tail, ending at the head.

No. Heap-based objects get destructed when you explicitly delete them, in the order that you delete them.
Stoffel
Stoffel
quote:
Original post by Pipo DeClown
~sStruct()
{
// safety checks
delete Next;
}


Sounds like you''re having each sStruct delete the next in the list. This is a Bad Thing. It''s inefficient & stack-hungry. You should instead have the LinkedList destructor delete each sStruct itself.
Pipo DeClown
Pipo DeClown
Okay, thanks.
Btw, this "Bad" thing is a thing that moderator Jim does

.lick

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.