Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Constructors have no return type. Just exactly why?

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.

like image 326
wonton Avatar asked Apr 27 '12 18:04

wonton


People also ask

Why don't constructors have a return type?

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.

Why can't I call constructors from my C++ code?

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.

How do you return a value from a constructor?

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.

Do C++ functions have to return anything?

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.


1 Answers

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).

like image 113
Ben Voigt Avatar answered Sep 28 '22 04:09

Ben Voigt