About the execution order of constructors and parent class constructors for subclass objects

Source: Internet
Author: User

We add an explicit constructor for the parent class and subclass, respectively, with the following code:

Class Person
{
private int nAge;
protected string StrName;
Double douheight;
public string Streatetype;
The constructor of the parent class
Public person ()
{
Console.WriteLine ("I am the constructor of the parent class");
}
public void Hello ()
{
Console.WriteLine ("I can say hello! ");
}
public void Run ()
{
Console.WriteLine ("I can run!" ");
}
}
Class Student:person
{
private string strclass;
private string straddress;
Constructors for subclasses
Public Student ()
{
Console.WriteLine ("I am a subclass constructor");
}
}

We use VS's Single-step debugging to see the execution order of the parent and subclass explicit constructors, such as (a dynamic picture, you can see the process):

It's easy to see, When creating child class objects
① The constructor of the subclass is called first
② called the constructor of the parent class
③ The constructor for the parent class
④ executes the constructor of the subclass

So why is that?
I tried to explain this by recompiling the source code, but the result of the anti-compilation is as follows,

There is no special place to explain the reason.

Finally, check out Microsoft's MSDN official documentation to find the answer (original address click here)

According to the official Microsoft code example, the following code has the same effect

//Constructors for subclasses Geneva         PublicStudent ()Geneva        {GenevaConsole.WriteLine ("I'm a subclass constructor."); to        } .//here the code and the above code effect is the same -         PublicStudent () ,            :Base() the        {TenConsole.WriteLine ("I'm a subclass constructor."); One        }

In other words, as long as the subclass explicitly declares the parameterless constructor, the object in the instantiation subclass is that the parameterless constructor of the subclass will call the parent class without a parameter constructor.
Then, if the parent does not have this parameterless constructor, it will get an error.
As in the following code:

class Person Geneva    {Geneva        Private intNAge;Geneva        protected stringStrName; to        DoubleDouheight; .         Public stringStreatetype; -        //the constructor of the parent class ,        //Public Person () the        //{Ten        //Console.WriteLine ("I am the constructor of the parent class"); One        //} A        //The parameter constructor of the parent class, which overrides the parameterless constructor -         PublicPerson (stringstr) -        { theConsole.WriteLine ("I am the parent class's constructor {0}", str); -        } -         Public voidHello () -        { +Console.WriteLine ("I can say hello!. "); -        } +         Public voidRun () A        { atConsole.WriteLine ("I can run! "); -        } -    } -    classStudent:person -    { -        Private stringstrclass; in        Private stringstraddress; -        //non-parametric constructors for subclasses to         PublicStudent () +        { -Console.WriteLine ("I'm a subclass constructor."); the        } *         PublicStudent (stringstrName) $        {Panax NotoginsengConsole.WriteLine ("My name is {0}", strName); -        } the    }

This time the compilation will error,

because a constructor with parameters in the parent class overrides a parameterless constructor, the parameterless constructor of the subclass does not have the option of calling back the parameterless constructor of the parent class to initialize the member variable of the parent class. So the error.


so why invoke the constructor of the parent class when the subclass is initialized?
The member variables of the parent class need to be initialized by the constructor before the subclass is initialized
What is the meaning of the constructor of the parent class that precedes the child class's constructor?
When you assign a different default value to a non-private member variable of the parent class in the constructor of the parent class and in the constructor of the child class. When instantiating a subclass, the subclass is calling the constructor to initialize the member variable, and if the constructor of the subclass is executed before the constructor of the parent class, the value of the parent class member field overrides the value of the Child class member field. But what we want is the property value of the child class. So in order to resolve data conflicts, the constructor of the parent class is performed before the constructor of the child class.
as in the following code:

class Person Geneva    {Geneva        Private intNAge;Geneva        Private stringStrName; to        DoubleDouheight; .         Public stringStreatetype; -       //the constructor of the parent class ,         PublicPerson () the        {Ten            //assign an initial value to Streatetype in the parent class One             This. Streatetype ="Eat"; AConsole.WriteLine ("I am the parent class's constructor {0}", streatetype); -        } -    } the    classStudent:person -    { -        Private stringstrclass; -        Private stringstraddress; +        //Constructors for subclasses -         PublicStudent () +        { A            //assigning an initial value to a streatetype in a subclass at             This. Streatetype ="Eat noodles"; -Console.WriteLine ("I'm a subclass of the constructor {0}", streatetype); -        } -    }

At this point we pass, declaring the subclass object to access the value of Streatetype, as follows:

New Student (); 2            // stu1. 3            string str = stu1.strEateType.ToString (); 4             Console.WriteLine (str); 5             Console.readkey ();

This must be to print out the value of the property Streatetype of the subclass, if the subclass constructor is executed first, and then the parent class's constructor assigns a value that overrides the initial value of Streatetype. Then the value of the parent class member field will be printed. Therefore, the constructor of the parent class is executed before the constructor of the child class.
The printing results are as follows:

SOURCE Link: The execution order of constructors and parent class constructors for subclass objects

About the execution order of constructors and parent class constructors for subclass objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.