I'm trying to develop a pretty simple (for now) wrapper class around int, and was hoping to overload the = operator to achieve something like the following:
class IntWrapper
{
...
private:
int val;
}
int main ( )
{
IntWrapper a;
int b;
a = 5; // uses overloaded = to implement setter
b = a; // uses overloaded = to implement getter
}
I'm gathering however that this can't be done. Implementing the setter is pretty straightforward, something like:
class IntWrapper
{
...
IntWrapper& operator = (int rhs) { this.val = rhs; return *this; }
...
}
However, from a bit of Googling I'm gathering there's no way to do the getter in this way. My understanding is that this is because the = operator can only be overridden to assign to a variable, and since int is a primitive type we cannot override its default implementation of =. Is this correct? If not, how do I go about writing the getter?
If that is correct, does anyone have any elegant suggestions for something similar? About the nearest I can find is overloading a conversion operator:
class IntWrapper
{
...
operator int( ) { return this.val; }
...
}
int main ( )
{
...
b = (int) a;
...
}
To me though that seems pretty pointless, as its barely any better than a simple getVal() method.
Thanks for any suggestions!