Classes: Explicit conversion operators




  • It is used to inhibit unintended implicit conversions to bool. Such conversion functions are called explicit conversion operators.

In the code below, we have the operator bool, but it’s not marked as explicit. When we want to do + and == calls on objects of type Test, the compiler will not find operator + (Test& other), but it can do an implicit cast to bool and then do the addition and compare on bools instead. This is not something that we would want in this case.


If we mark the operator bool as explicit, the addition and comparison will fail at compile, because the compiler cannot find the overriden function operator+(Test&) AND cannot do an implicit cast to bool.


If we want to have the following operations, we will have to define them ourselves.

You may also like...

Leave a Reply