The following link mentions that the constructor returns current class instance and that we can write "return " inside a constructor …
What does this mean?
Here is the link :
Also , is it the same thing in C++ also ?
The following link mentions that the constructor returns current class instance and that we can write "return " inside a constructor …
What does this mean?
Here is the link :
Also , is it the same thing in C++ also ?
I think the confusion is purely notational.
You declare a constructor like:
public class Hello {
public Hello() {}
}
The syntax for instantiating an object is as follows:
Hello hello = new Hello();
This creates a new object by allocating memory and calling the constructor. Which will clearly result in an instance of Hello class.
Constructor get automatically envoked when an object is instantiated.
One way to reconcile the apparently conflicting notation is by thinking of a constructor as returning the object being constructed, but doing so implicitly.
As you have learned that constructors don’t have any return type, not even void.
Therefore, you cannot have a return statement with any value inside the constructor.
Example:
public class Hello {
public Hello() {
return value;
/where value can be of any data type(like into,
float, char) or void/
}
}
This is an invalid statement.
But you can write a return statement without mentioning any value(not even void)
Example:
public class Hello {
public Hello() {
return;
}
}
This valid code.
Hope this will help you. If you still have any doubts, feel free to ask.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
In the second point that you have mentioned , may I know where can we use this thing practically in programming ?
I know it’s weird to believe. But there is no practical use of it.
alright , what is the use ?