Preventing implicit cast of numerical types in constructor in C++
-
21-09-2019 - |
Question
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?
Solution
What's your compiler? Under gcc, you can use -Wconversion
to warn you about these types of conversions.
OTHER TIPS
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.
Declare a private MyClass(double a, double b, double c)
constructor.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow