wootscootinboogie
wootscootinboogie

Reputation: 8695

Using base and this in constructor chaining

Say there is a base class called Employee that looks like the following

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 a class Manager which inherits from Employee with a constructor like

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

To the best my understanding, the this keyword is just like the base keyword only it applies to constructors in the same class. My biggest question is, while reading a reference book, it says if you don't use the chaining the construction of a Manager object will include seven 'hits'. Since Manager inherits from Employees, does this mean that every Manager object is 'born' as an Employee and then becomes a Manager later? And after it is a manager you only have two fields to add instead of seven?

Upvotes: 5

Views: 7307

Answers (2)

Dughall
Dughall

Reputation: 719

In .NET, the complete object is created before any constructors get called. Next, the base constructor is called, then the derived class constructor.

So the answer is no - the manager object is not born as an employee and becomes a manager later. Rather, the manager object is born as a manager object ... before constructors get called.

BTW, in non-managed C++, it's the opposite, although enough memory is allocated for the derived class, the Employee object is created first (calling the Employee constructor) and any virtual methods called will result in despatching to the base class method bodies. Then the Manager class gets constructed.

Upvotes: 5

Justin Harvey
Justin Harvey

Reputation: 14672

Yes, that is it.

The contructor parameters flow from the bottom up, then the object is created from the top down. It has to be like this in case your derived class need to access base class members in its constructor.

Upvotes: 5

Related Questions