Pages

2011-02-21

C++: Prevent the compiler from doing implicit type conversion

Use the keyword explicit on the constructor. Forcing explicit conversions is usefull
to make the programmers aware of the conversion. This is especially interesting for
time consuming conversions.
struct A
{
A() {}
};

struct B
{
B() {}
B(const A &a) {}
};

struct C
{
C() {}
explicit C(const A &a) {}
};

void fb(B b) { /* ... */ }

void fc(C c) { /* ... */ }

void function()
{
A a;
B b;
C c;
fb(a); // ok, conversion is implicit
fc(a); // error
fc(C(a)); // ok, conversion is explicit
}

No comments:

Post a Comment