Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloaded cast operator or single argument constructor

If a class has a single argument constructor my understanding is it is implicitly convertible by the constructor to the type of the argument in appropriate contexts. Defining a conversion operator also makes a class convertible to another type. Questions

  • Does the conversion operator ever get called implicitly?
  • If both a single argument constructor and conversion operator with the same type are defined for a class does one have precedence over the other or is it ambiguous?
  • If you've decided that you want a class to be convertible to a given type, which approach is better or should you provide both?

Edit:

I see I didn't understand clearly the directionality and that the two perform conversions in the opposite directions. As a follow on

  • If you have control over two classes that you want to make convertible to and from each other is there a preferred way in terms of these two operations to accomplish this?
  • Is it possible mark the conversion operator as explicit?
like image 809
bpw1621 Avatar asked Aug 11 '10 17:08

bpw1621


1 Answers

These two are opposites: non-explicit one-argument constructor allows for automatic type conversion to your class type from argument type. Conversion operator allows for implicit casting from your class type.

Common wisdom is to avoid both if not specifically required.

like image 176
Nikolai Fetissov Avatar answered Nov 11 '22 22:11

Nikolai Fetissov