I've Googled this and read many posts, but there are so many different answers that all make logical sense that I was wondering if an expert on the topic could demystify this question.
Some say that there is no return because there is no way to return - the syntax prohibits it - yes, this makes sense, but I believe that all functions have to return something, no? Others say that the constructor sort of returns the newly created object itself, which seems to make sense since the assignment operator is used on the constructor. Still others have other interesting explanations.
When you call a constructor the return value is the new object: But within the constructor itself, you're not actually creating and returning the object; it's been created before your code starts, you're just setting up the initial values. The lack of a return type reflects the fact that constructors are used differently than other functions.
You can't call constructors from your C++ code because constructors don't have a name. Making constructors not have a return type emphasizes to the programmer that constructors are a very different kind of function than other functions.
By definition there is no possibility of returning a value from a constructor.A constructor does not support any return type. Not even void. The implicit return type by default is the class type in which it is declared. Constructors are meant to initialize the instance variables.
The code can't set a return value and calling code can get any return value. So no, functions don't have to return anything. That constructors lack a return type -- not even void -- means that you can't call a constructor from your C++ code. And that's the point.
Constructors aren't called like other functions, so they don't return like other functions. They execute as a side-effect of certain constructs (cast, new
, variable definition, ctor-initializer-list, pass-by-value, return-by-value).
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