c++ – Type casting in initialization lists, which is better?

Question:

I have a std::uint64_t m_value field in my class. In the default constructor, I write in the initialization list : m_value(0) . I work with different compilers, and you can adjust the output of warnings in the project settings. Some do not react in any way to such initialization, some write something about type casting.

The question is: should we continue to write like this or should we explicitly write a type cast, for example : m_value((std::uint64_t)(0)) , or through static_cast ? What is considered the best way to do it? I understand that implicit type casting is of course performed, but maybe it makes sense for the person reading the code to show what was meant?

Answer:

There is no point in using type casting. 0 is a constant expression, one might say, a "universal" literal for scalar and even more so arithmetic types. In addition, all static objects are zero-initialized by the compiler, so the use of 0 in this context in the constructor initialization list looks quite natural and does not raise questions. On the contrary, the use of type casting can raise questions about why this is done.

Scroll to Top