views:

112

answers:

2

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!

+4  A: 

You don't need a cast to invoke the conversion function. A plain

b = a;

will invoke it too. That way, i can see how that's more convenient to use than a getVal function. Although i generally don't use conversion functions. I would prefer an explicit getVal function. In particular consider this one

struct W {
  W(int);
  operator int();
};

int main() {
  W w = 42;
  int a = true ? 0 : w; // Ambiguity! What conversion direction?
}

It quickly gets out of hand...

Johannes Schaub - litb
Ah, excellent. Thanks very much.
Mac
+1  A: 

What you suggest is the way to go, and I use it all the time. You shouldn't need to cast a to an int. The compiler is smart enough to see the b is an int and it will automatically call the operator int cast operator for you.

miked
Thanks to you too!
Mac