Joseph Caruso Joseph Caruso - 2 months ago 22
C++ Question

C++ custom type

I've got a class

int32
, and it is set up in a way that it can essentially be interfaced with as an
int
(operator overloads), but there's one part I don't get.

int32 i32 = 100; // Works
int i = 200; // Works
i32 += 10; // Works
i32 -= 10; // Works, i32 = 100 right now
i = i32; // Doesn't work


What operator would I need to overload to achieve referencing i32 returning it's stored value, in this case, 100 (or how else could it be done)?

Answer

You could add a conversion operator operator int:

class int32 {
public:
    operator int() const;
    ...
};

Note that it comes in two flavours. The above will allow

int32 foo;
int i = foo;

If you define the conversion operator as explicit

    explicit operator int() const;

then the above will fail by design, and require an explicit cast:

int32 foo;
int i = static_cast<int>(foo);