Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the constructor get called in the reverse order?

Tags:

c#

.net

c#-4.0

In the inheritance why the base class constructor get the call first why not the derived one??

like image 436
Archana Virmani Avatar asked Oct 04 '10 09:10

Archana Virmani


People also ask

Why destructors are called in reverse order?

Objects are always destroyed in reverse order of their creation. The reason for reverse order is, an object created later may use the previously created object.

Why parent constructor is called first?

So if in the initialization process of child class there may be the use of parent class members. This is why the constructor of the base class is called first to initialize all the inherited members.

In what order are constructors called?

The answer is that in a class hierarchy, constructors are called in order of derivation, from superclass to subclass. Further, since super( ) must be the first statement executed in a subclass' constructor, this order is the same whether or not super( ) is used.

Which constructor is executed first?

Order of execution of constructor in Single inheritance In single level inheritance, the constructor of the base class is executed first.


2 Answers

To make sure the public or protected members of the base-class are properly initialized before they are used in the derived class.
To be precise, the derived-class constructor is run first with an implicit call to the base-class constructor inserted as the first statement in the body of the derived-class constructor by the compiler (assuming default no-arg constructors).

like image 175
Zaki Avatar answered Oct 03 '22 15:10

Zaki


The derived class is created by extending the base class. It should be ensured that the base class members are properly initialized, before it can be extended in a derived class. Also, members initialized in derived class should not be overridden by base class.

like image 39
Joyce Babu Avatar answered Oct 03 '22 14:10

Joyce Babu