Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Defining a type cast

Tags:

c++

casting

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 &ampv)
    {
        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.
like image 695
helloworld922 Avatar asked Jan 28 '11 02:01

helloworld922


1 Answers

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;
}
like image 114
casablanca Avatar answered Nov 06 '22 10:11

casablanca