Explicit Constructor in C++

A C++ constructor acts like an implicit type converter whenever it is needed. In the example below, the Foo( int ) constructor acts like an int-to-Foo type converter for the function doSomething.

class Foo
{
public:
	Foo( int x ) { _val = x; }
private:
	int _val;
};

void doSomething( const Foo &foo )
{}

doSomething( 10 ); // Acts like doSomething( Foo( 10 ) );

Only constructors with one non-default parameter can act like implicit convertors. That is, a constructor with only one parameter, which is not a default parameter. Or a constructor with many parameters, where the first parameter is not default and the rest of the parameters are default parameters. In the example below, the constructor with many parameters also acts like an implicit int-to-Foo convertor since all but one are default parameters.

class Foo
{
public:
	Foo( int x, int y = 99, int z = 999 ) { _val = x; }
private:
	int _val;
};

void doSomething( const Foo &foo )
{}

doSomething( 10 );

With the inherent complexity of C++, most programmers do not want such implicit conversions happening under the hood. To prevent this from happening, the explicit qualifier can be used on such constructors. The example below does not allow implicit conversion.

class Foo
{
public:
	explicit Foo( int x ) { _val = x; }
private:
	int _val;
};

void doSomething( const Foo& foo )
{}

doSomething( 10 );        // Error!
doSomething( Foo( 10 ) ); // OK

A few notes:

  • The explicit qualifier can be used only with the constructor declaration, not the definition (if the two are separate).
  • The explicit qualifier can be used on any constructor. Even the default constructor or constructors with many non-default parameters. It is allowed for these, but does not seem to serve any purpose.

Since explicit prevents such under-the-hood activities, it is a good habit to apply it by default on all constructors. Turn it off only when you actually need an implicit conversion. 🙂

Advertisements

One thought on “Explicit Constructor in C++”

  1. void doSomething(const Foo& foo)
    {}

    what is Foo&amp never seen anything in the param declaration, Has this one imply any meaning.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s