What if I write return statement in constructor? Is it standard conformant?
struct A
{
A() { return; }
};
The above code compiles fine, without any error at ideone. But the following code doesn’t:
struct A
{
A() { return 100; }
};
It gives this error at ideone:
error: returning a value from a constructor
I understand that returning value from constructor doesn’t make sense at all, because it doesn’t explicitly mention return type, and we cannot store the returned value after all. But I’m curious to know :
- Which statement from the C++ Standard allows the first example but forbids the second one? Is there any explicit statement?
- Is the return type in the first example
void? - Is there any implicit return type at all?
Yes, using return statements in constructors is perfectly standard.
Constructors are functions that do not return a value. The family of functions that do not return a value consists of: void functions, constructors and destructors. It is stated in 6.6.3/2 in the C++ standard. The very same 6.6.3/2 states that it is illegal to use
returnwith an argument in a function that does not return a value.Additionally, 12.1/12 states that
Note, BTW, that in C++ it is legal to use
returnwith an argument in a void function, as long as the argument ofreturnhas typevoidThis is not allowed in constructors though, since constructors are not void functions.
There’s also one relatively obscure restriction relevant to the usage of
returnwith constructors: it is illegal to usereturnin function-try-block of a constructor (with other functions it is OK)