December 2018
Intermediate to advanced
702 pages
20h 9m
English
We have already seen that a constructor can be used to convert from another type to your custom type if your custom type has a constructor that takes the type you are converting. You can also perform the conversion in the other direction: converting the object into another type. To do this, you provide an operator without a return type with the name of the type to convert to. In this case, you need a space between the operator keyword and the name:
class mytype { int i; public: mytype(int i) : i(i) {} explicit mytype(string s) : i(s.size()) {} operator int () const { return i; } };
This code can convert an int or a string to mytype; in the latter case, only through an explicit mention of the constructor. ...
Read now
Unlock full access