8
votes

I have a constructor of the form:

MyClass(int a, int b, int c);

and it gets called with code like this:

MyClass my_object(4.0, 3.14, 0.002);

I would like to prevent this automatic conversion from double to int, or at least get warnings at compile time.

It seems that the "explicit" keyword does not work in these case, right?

3
A cast is explicit by definition. You mean "implicit conversion" in the title. - Alok Singhal

3 Answers

9
votes

What's your compiler? Under gcc, you can use -Wconversion to warn you about these types of conversions.

5
votes

Declare a private constructor like this:

private:
template <class P1, class P2, class P3>
MyClass(P1,P2,P3);

That will cause a compile time error for any construction using 3 parameters that aren't all int, and it's portable.

2
votes

Declare a private MyClass(double a, double b, double c) constructor.