C++ Programming - Explicit Constructors


class A {
public:
A() { ... };
A(int i) { ... };
};

main()
{
A a;
A b = 1;
...
}


The compiler interprets the expression A b= 1; as if the programmer had written
A b = A(1);


You might encounter a similar problem when calling a function that takes A as argument. The following example can either be a cryptic coding style or simply a programmer's typographical error. However, due to the implicit conversion constructor of class A, it will pass unnoticed:


int f(A a);
int main()
{
f(1); // without a an explicit constructor,
//this call is expanded into: f ( A(1) );
//was that intentional or merely a programmer's typo?
}


In order to avoid such implicit conversions, a constructor that takes one argument needs to be declared explicit:


class A {
public:
A() { ... };
explicit A(int i) { ... };
};

An explicit constructor does not behave as an implicit conversion operator, which enables the compiler to catch the typographical error this time:

int main()
{
A a; //OK
A b = 1;// compile time error ; this time the compiler catches the typo
}

Labels:


About this entry