I need to call one constructor from the body of another one. How can I do that?
Basically
class foo { public foo (int x, int y) { } public foo (string s) { // ... do something // Call another constructor this (x, y); // Doesn't work foo (x, y); // neither } }
Example 1: Java program to call one constructor from another Here, you have created two constructors inside the Main class. Inside the first constructor, we have used this keyword to call the second constructor. this(5, 2); Here, the second constructor is called from the first constructor by passing arguments 5 and 2.
No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.
No, in C++ you cannot call a constructor from a constructor.
Constructor chaining is the process of calling one constructor from another constructor with respect to current object.
You can't.
You'll have to find a way to chain the constructors, as in:
public foo (int x, int y) { } public foo (string s) : this(XFromString(s), YFromString(s)) { ... }
or move your construction code into a common setup method, like this:
public foo (int x, int y) { Setup(x, y); } public foo (string s) { // do stuff int x = XFromString(s); int y = YFromString(s); Setup(x, y); } public void Setup(int x, int y) { ... }
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