When we are defining class we sometimes would like to allow easily convert that class from and to previously defined-type objects (ex. int). We can do that using conversion constructor and conversion operator:
Output of this example is:
In that example in our class TestClass we are defining two conversion constructors.
In point III and IV we are defining two conversion operator (into type int and string). As you can see in points VII and VIII, those conversion operators allows us convert object of TestClass to object of int or string.
Now take a look at points IX and X. We you uncommet it you will receive compiler error. It is because we have defined neither conversion constructor nor conversion operator for type char*.
I hope you understood how to define and how to use conversion constructor and conversion operator.
If you have any questions or suggestions, write in comments, please.
Code for this example you can find and download here:
https://github.com/xmementoit/CppAdventureExamples/tree/master/advancedCpp/conversionConstructorAndOperatorhttps://github.com/xmementoit/CppAdventureExamples/tree/master/advancedCpp/conversionConstructorAndOperator
- conversion constructor - it is constructor which has one parameter - type which constructor should allow to convert from. It allows to convert previously defined object of type as in constructor paramter into object of class where constructor belongs to
- conversion operator - it is overloaded operator type() - where type is type of object which we can convert this class object into
Output of this example is:
In that example in our class TestClass we are defining two conversion constructors.
- conversion constructor for type int (point I)
- conversion constructor for type string (point II)
In point III and IV we are defining two conversion operator (into type int and string). As you can see in points VII and VIII, those conversion operators allows us convert object of TestClass to object of int or string.
Now take a look at points IX and X. We you uncommet it you will receive compiler error. It is because we have defined neither conversion constructor nor conversion operator for type char*.
I hope you understood how to define and how to use conversion constructor and conversion operator.
If you have any questions or suggestions, write in comments, please.
Code for this example you can find and download here:
https://github.com/xmementoit/CppAdventureExamples/tree/master/advancedCpp/conversionConstructorAndOperatorhttps://github.com/xmementoit/CppAdventureExamples/tree/master/advancedCpp/conversionConstructorAndOperator
Nice article thanks for that information.
ReplyDelete