Order of constructor and destructor invocation

A

aarti.sanga

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
 
A

Amal P

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.
 
R

Ron Natalie

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top