Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What actually Base Keyword does in Constructor initialization?

Tags:

c#

constructor

I have been confused by the base keyword in C#. Say I have some code like this:

​class A
{
    ​// member declaration....
    A(int s, int t, int x)
    {
        ​// assign the values of members
    }
}

class B : A
{
    // member declaration....
    ​B(int a, int b, int c, int d) : base(a,b,c)
    {
        // does the base keyword play a role in
        // this constructor?
    }
}
​

Now what is the exact use of base keyword in B's constructor? I have few questions to clarify:

  1. Using the base keyword will call the base class A constructor(in our example)? Is this correct?
  2. Providing the base keyword in derived class changes the behavior of the derived class constructor?

And basically when base keyword should be used in the constructor(some examples would be good)?

Edit:

I have another question. How can I inform the base class about our derived class, via base keyword?

Thanks in advance.

like image 882
Ant's Avatar asked Nov 17 '11 15:11

Ant's


People also ask

What is the purpose of base keyword?

The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class.

Is Base constructor called first?

The compiler knows that when an object of a child class is created, the base class constructor is called first.

Which keyword is used to base construct constructor subclass constructor?

For super keyword in Java, we have the base keyword in C#. Super keyword in Java refers immediate parent class instance. It is used to differentiate the members of superclass from the members of subclass, if they have same names. It is used to invoke the superclass constructor from subclass.

Why is base constructor called first in C++?

A technical reason for this construction order is that compilers typically initialize the data needed for polymorphism (vtable pointers) in constructors. So first a base class constructor initializes this for its class, then the derived class constructor overwrites this data for the derived class.


1 Answers

Yes - base chains to a constructor in the base class.

If you don't specify base or this (to chain to another constructor in the same class), the effect is as if you had base() chaining to a parameterless constructor in the base class. In your example this would cause a compilation failure as your base class doesn't have a parameterless constructor.

See my article on constructors for more information.

like image 188
Jon Skeet Avatar answered Sep 21 '22 15:09

Jon Skeet