Is there a way to define a type cast from say a user defined class to a primitive type (int, short, etc.)? Also, would any such mechanism require an explicit cast, or would it work implicitly?
for example:
// simplified example class
class MyNumberClass
{
private:
int value;
public:
// allows for implicit type casting/promotion from int to MyNumberClass
MyNumberClass(const int &v)
{
value = v;
}
};
// defined already above
MyNumberClass t = 5;
// What's the method definition required to overload this?
int b = t; // implicit cast, b=5.
// What's the method definition required to overload this?
int c = (int) t; // C-style explicit cast, c=5.
// ... etc. for other cast types such as dynamic_cast, const_cast, etc.
Yes, you can define an operator type()
to do the conversion, and yes, it will work implicitly whenever such a conversion is required:
operator int() {
return value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With