Using the base and this in the chain of constructors

Let's say that there is an Employee base class that looks like this

 public Employee(string name, int id, float pay) : this(name, 0, id, pay, "") { } public Employee(string name, int age, int id, float pay, string ssn) { // Better! Use properties when setting class data. // This reduces the amount of duplicate error checks. Name = name; Age = age; ID = id; Pay = pay; SocialSecurityNumber = ssn; } 

And the Manager class that inherits from the Employee type constructor

 public Manager(string fullName, int age, int empID, float currPay, string ssn, int numbOfOpts) : base(fullName, age, empID, currPay, ssn) { . StockOptions = numbOfOpts; } 

As far as I know, the this keyword is similar to the base keyword, it applies only to constructors of the same class. My biggest question is that, reading the manual, he says that if you do not use the chain, the construction of the Manager object will include seven hits. Since the Manager inherits from Employees, does this mean that each manager object is โ€œbornโ€ as an Employee, and then becomes a Manager later? And after this is a manager, you have only two fields to add instead of seven?

+4
source share
2 answers

Yes, thatโ€™s all.

The constructor parameters flow from the bottom up, then the object is created from top to bottom. This should be so if your derived class needs to access the elements of the base class in its constructor.

+5
source

In .NET, an entire object is created before all constructors are called. Then the base constructor is called, then the constructor of the derived class.

Thus, the answer is no: the manager object is not born as an employee and later becomes a manager. Rather, an object manager is born as an object manager ... before calling constructors.

BTW, in unmanaged C ++, on the contrary, although enough memory is allocated for the derived class, the Employee object is first created (a call to the Employee constructor), and any calls to virtual methods will result in methods being sent to the base class. Then the Manager class is created.

+4
source

Source: https://habr.com/ru/post/1439406/


All Articles