Connecting Tech Pros Worldwide Forums | Help | Site Map

Order of constructor and destructor invocation

aarti.sanga@gmail.com
Guest
 
Posts: n/a
#1: Jun 21 '07
Hi,

I know that when a class is created the contructors of its base
classes are called, followed by the constructors of its data members,
in the order in which they appear in the class. One reason for this
is that the derived class may be using the members of the base class.
Can someone show me an example of this? Also why are destructors
always invoked in the reverse order of constructor invocation?

Thanks in advance


Amal P
Guest
 
Posts: n/a
#2: Jun 21 '07

re: Order of constructor and destructor invocation


On Jun 21, 2:10 pm, aarti.sa...@gmail.com wrote:
Quote:
Hi,
>
I know that when a class is created the contructors of its base
classes are called, followed by the constructors of its data members,
in the order in which they appear in the class. One reason for this
is that the derived class may be using the members of the base class.
Can someone show me an example of this? Also why are destructors
always invoked in the reverse order of constructor invocation?
>
Thanks in advance
Hi,

Derived class uses the resource of base class. If the derived class is
constructed before base class it will be a since derived class may try
to access base class resource before base class has not been
constructed. So the base class is destructed first. Same is the case
with derived class also. If we destruct base class first and the
derived class is still accessing it it will also cause problem. So
this order is always maintained.

Thanks and regards,
Amal P.

Ron Natalie
Guest
 
Posts: n/a
#3: Jun 21 '07

re: Order of constructor and destructor invocation


aarti.sanga@gmail.com wrote:
Quote:
Hi,
>
I know that when a class is created the contructors of its base
classes are called, followed by the constructors of its data members,
in the order in which they appear in the class. One reason for this
is that the derived class may be using the members of the base class.
Can someone show me an example of this? Also why are destructors
always invoked in the reverse order of constructor invocation?
>
Thanks in advance
>
Initialization actually goes like this:

Only for the most derived class: The virtual base classes of the entire
tree are invoked.

Then starting with the most derived class and working recursively:

1. The direct (non-virtual) bases are initialized
2. The non-static members are initialized
3. The constructor body runs

Your supposition is correct, derived classes build upon the base classes
so they have to be done before the derived class starts initializing its
own pieces. The derived knows about the base, but the base doesn't
know about the derived.

Destruction happens in the opposite order for the same reason, the
derived parts need to go away because they know about the base.
Once they're disposed of, the base can go away.
Closed Thread