Samaursa
Samaursa

Reputation: 17271

Empty return in Constructor

I expected Visual Studio to give me an error or at the very least a warning, but it gave me neither when I had an empty return in the constructor:

MyObject::MyObject()
{
    if (/*some condition*/)
    {
        //SomeCode
        return;
    }

    // continue with other code
}

I have not seen usage of this so far in my limited experience, so my question is whether it is OK to have a return in the constructor?

This is more of a curiosity question as I understand that it is very easy to code such that you never have to put return in there, although I have an instance where this would be very useful, but before using it I want to see if it is prohibited (maybe by the standard or is, in general, not a good idea).

Upvotes: 10

Views: 750

Answers (2)

Khaled Alshaya
Khaled Alshaya

Reputation: 96939

The standards say:

12.1 Constructors
...
A return statement in the body of a constructor shall not specify a return value. The address of a constructor shall not be taken.
...

It is OK to have return; in a constructor. My understanding is that this was allowed so that the programmer can return early from the constructor without the need for making a mess with boolean flags.

Upvotes: 12

dennycrane
dennycrane

Reputation: 2331

It's ok. It means the object has been constructed successfully. It should not bite you if you follow the general advice of initializing member variables in the initializer list. It's similar to the innocent looking following code.

MyObject::MyObject () {
    if (/* something */) {
        // SomeCode
    } else {
        // continue with other code
    }
}

Upvotes: 5

Related Questions