Search code examples
c++operator-overloadingclarity

In what situations is using operator cast more useful than confusing?


In C++, the use of operator cast can lead to confusion to readers of your code due to it not being obvious that a function call is being invoked. That being said, I've seen its use being discouraged.

However, under what circumstances would using operator cast be appropriate and have value which exceeds any possible confusion it might lead to?


Solution

  • When the conversion is natural and has no side effects it can be useful. Nobody is going to argue that an automatic conversion from int to double is inappropriate for example, even if you can come up with a corner case that makes it confusing (and I'm not sure anybody can).

    I've found the conversion from Microsoft's CString to const char * to be incredibly handy, even though I know others disagree. I wouldn't mind seeing a similar capability in std::string.