Constructor calling itself

I recently found out that the argument constructor and the multiple argument constructor cannot take turns exchanging with each other. What is the reason for this limitation? Some may say that constructors are where resources are initialized. Therefore, they cannot be called recursively. I want to know if this is the only reason or not. Functions / methods / procedures can be called recursively. Why not the constructors?

+4
source share
5 answers

The answer is that calling another constructor is the first line of any constructor, and therefore the if condition for exiting the recursion will never be met, and therefore the stack will overflow.

+5
source

The main purpose of the constructor is to initialize all global variables described in a particular class.

For Example: public class Addition(){ int value1; int value2; public Addition(){ // default constructor a=10; b=10; } public Addition(int a, int b){ this(); // constructors having parameters , overloaded constructor value1=a; value2=b; } } public class Main(){ public static void main(){ Addition addition = new Addition(); //or Addition addition = new Addition(15,15); } } Here, if you want to make instance of the class you can either make instance by calling default constructor or by calling constructor having parameters. So the constructors are overloaded and not overridden. If you want to call another constructor, that can only be done be putting either this() or super() in the first line of the constructor. But this is not prefferable. 
+2
source

Constructors are not intended to explicitly initialize an external object, because they are limited in most (I think, all) languages. Instead, you can create an additional member function protected Init(...) and call it inside the constructor.

+1
source

Your statement that a constructor cannot call other constructors is not true for every programming language. At least I know that Java can do this, but C ++ cannot. But you can easily overcome this limitation by writing a private __init function and let all its constructors call it.

+1
source

In all the languages ​​you specify, objects contain a finite (and usually short) set of properties. Each property may contain a recursive structure (i.e. List), but it is still represented by a single property in the object.

I don't see the need to call constructors recursively. This is similar to a strange use recursion to initialize several well-known properties.

As you said, you can invoke constructors in a non-recursive way to share code in some of the languages ​​you mentioned.

C #: Using Constructors

 public Employee(int weeklySalary, int numberOfWeeks) : this(weeklySalary * numberOfWeeks) { } 
+1
source

Source: https://habr.com/ru/post/1404040/


All Articles