Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling base constructor passing in a value

Tags:

c#

public DerivedClass(string x) : base(x)
{
  x="blah";
}

will this code call the base constructor with a value of x as "blah"?

like image 200
raklos Avatar asked Jun 18 '09 11:06

raklos


People also ask

How do you call a base class constructor?

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.

Can we pass parameters to base class constructor through derived?

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.

How do you call a base constructor in Java?

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.

Can we inherit base class constructor?

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.


2 Answers

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.

like image 107
Jon Skeet Avatar answered Oct 09 '22 14:10

Jon Skeet


No, base call we be performed before executing the constructor body:

//pseudocode (invalid C#):
public Constructor(string x) {
   base(x);
   x = "blah";
}
like image 37
mmx Avatar answered Oct 09 '22 13:10

mmx