I was wondering if there is a difference between the methods of conversion, and if one is better than the other.
Suppose there is a class A and a class B. class B can be converted to a class A. Say for example class A is something representing a string, and class B is something representing an integer.
You could obtain a class A object from a class B object in a number of ways:
operator A()function inclass Bto allow implicit conversionexplicit operator A()function inclass Bto allow explicit conversionA toA()function inclass B, to effectively convert itstatic A parse(B)function inclass Ato convert itA(B)constructor inclass Ato create a new object
Is there any preferred way of converting the object? Should multiple ways be implemented? Should any be avoided? Or is it all context-based, and should it be determined by best judgment?
AtoBthrough the use of their public interfaces then make a free conversion function, much like the standard library does withstd::to_stringorstd::stoi. - user657267explicitthe problems related to implicit conversions have gone. The great thing about free functions though is they decrease coupling, neitherAnorBwould be responsible for the conversion, they don't need to know anything about the other's interface. Use conversion operators if you think they de-clutter your code and are easy for the user to understand (and you aren't worried about the dependency). - user657267