[C++] Deconstruction order of member variables...

This topic is 3859 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

This is a pretty quick question, which I think I already know the answer to... If a class has a number of member variables, is the order in which they are destroyed defined? [Edited by - fpsgamer on October 29, 2007 4:42:24 PM]

Share on other sites
In the opposite order of the completion of their constructors.

Share on other sites
Quote:
 Original post by jpetrieIn the opposite order of the completion of their constructors.

Can anything be said about the order of construction?

class FooBar
{
public:
Foo f;
Bar b;
...
};

So in the above example, will f get constructed then b simply because I have declared them in that oder?

Share on other sites
In this particular example, yes. This is only the case because they are within the same access specifier.

Share on other sites
"order of construction - a class object is constructed from the bottom up: first bases in declaration order, then members in declaration order, and finally the body of the constructor itself. TC++PL 10.4.6, 12.2.2, 15.2.4.1, 15.4.3. D&E 2.11.1, 13.2.4.2."

From:
http://www.research.att.com/~bs/glossary.html#Gorder-of-construction

Share on other sites
You can destruct/delete a class member(class)variables in it's destructor, like this:

class SomeClass{...SomeOtherClass *memberClassVar1;SomeOtherClass *memberClassVar2;...   ~SomeClass()   {      delete memberClassVar1;      delete memberClassVar2;   }};

Just an idea i got.

Share on other sites
Quote:
 Original post by programeringYou can destruct/delete a class member(class)variables in it's destructor, like this:*** Source Snippet Removed ***Just an idea i got.

Destruction and deletion are 2 different things.

Share on other sites
Quote:
 You can destruct/delete a class member(class)variables in it's destructor, like this:

Of course, that's not really what he was asking. Also, that clearly won't be useful unless you allocate every member on the heap. Which is not a good idea. At all.

Share on other sites
Quote:
 Original post by ToohrVykIn this particular example, yes. This is only the case because they are within the same access specifier.

Access specifiers don't affect order of initialization of members. This implies that members may be initialized in a different order than their relative order in memory.

Share on other sites
Quote:
 Original post by jpetrieIn the opposite order of the completion of their constructors.

Obligatory addition for the virtual inheritance and more convoluted hierarchies.

• 9
• 13
• 41
• 15
• 14