public DerivedClass(string x) : base(x)
{
x="blah";
}
will this code call the base constructor with a value of x as "blah"?
You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class. Example: Javascript.
If you are using your derived class constructor just to pass arguments to base class then you can also do it in a shorter way in C++11: class B : public A { using A::A; }; Also you may refer to https://softwareengineering.stackexchange.com/a/307648 to understand limitations on constructor inheritance.
A derived Java class can call a constructor in its base class using the super keyword. In fact, a constructor in the derived class must call the super's constructor unless default constructors are in place for both classes.
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
The base call is always done first, but you can make it call a static method. For example:
public Constructor(string x) : base(Foo(x))
{
// stuff
}
private static string Foo(string y)
{
return y + "Foo!";
}
Now if you call
new Constructor("Hello ");
then the base constructor will be called with "Hello Foo!".
Note that you cannot call instance methods on the instance being constructed, as it's not "ready" yet.
No, base
call we be performed before executing the constructor body:
//pseudocode (invalid C#):
public Constructor(string x) {
base(x);
x = "blah";
}
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