Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Explicit Constructor in C++

📅 2010-Dec-17 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

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:

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