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:
base
keyword will call the base class A
constructor(in our example)? Is this correct?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)?
I have another question. How can I inform the base
class about our derived
class, via base
keyword?
Thanks in advance.
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.
The compiler knows that when an object of a child class is created, the base class constructor is called first.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With