Monday, April 07, 2008

C++ : Preventing implicit type conversion

class Foo{
public:

Foo(int n ){
...
}

};

Foo foo(42);
Foo boo = 42;

In the above mentioned snippet , the first constructor is matched and called. In the second case , for the assignment operator since the right hand side is 42 and since we have a constructor that takes integer as an argument . The corresponding constructor is called . This is syntactic sugar that can lead to lots of problems . To prevent something like this .

the explicit keyword should be used in front of constructors .

No comments: