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

Started by
19 comments, last by rip-off 16 years, 5 months ago
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]
Advertisement
In the opposite order of the completion of their constructors.
Quote:Original post by jpetrie
In 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?
In this particular example, yes. This is only the case because they are within the same access specifier.
"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
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.
Quote:Original post by programering
You 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.
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.
Quote:Original post by ToohrVyk
In 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.
Quote:Original post by jpetrie
In the opposite order of the completion of their constructors.


Obligatory addition for the virtual inheritance and more convoluted hierarchies.

This topic is closed to new replies.

Advertisement