Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call base constructor and other constructor in constructor

Tags:

Title may sound confusing. What I want is to call a constructor of the same class and the constructor of the base class inside a constructor. Maybe my first attempt to solve that may explain my question:

public MyClass(MyClass obj) : base(obj),this() {} 

But that notation isn't working. Is there any solution to solve that?

like image 997
Kai Avatar asked Jun 16 '11 07:06

Kai


People also ask

Can we call constructor from another constructor?

The invocation of one constructor from another constructor within the same class or different class is known as constructor chaining in Java. If we have to call a constructor within the same class, we use 'this' keyword and if we want to call it from another class we use the 'super' keyword.

Can a constructor call another constructor of the same class?

Calling a constructor from the another constructor of same class is known as Constructor chaining. The real purpose of Constructor Chaining is that you can pass parameters through a bunch of different constructors, but only have the initialization done in a single place.

Which constructor will call first?

Order of constructor call for Multiple Inheritance For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.


2 Answers

No, you can't do it for the following reason:

When a constructor calls the constructor of its base, the latter call is THE PART of the constructor in question. So you can't call another constructor of the same class AND a constructor of a base class because the former call already contains a call to a base constructor - you can't initialize your base twice

like image 170
Armen Tsirunyan Avatar answered Sep 17 '22 13:09

Armen Tsirunyan


C# allows either base(...) or this(...), because every constructor must eventually invoke a super constructor. So if it were possible to invoke both base() and this(), two super constructors invocations would take place, which would be fundamentally incorrect.

It is the same reason why it is not possible to invoke base(...) twice.

like image 41
Nick Avatar answered Sep 18 '22 13:09

Nick