0

I'm currently trying to refactor some code which uses a primitive type into something which I can tuck setters and getters into them. I wanted to make the change to the underlying code transparent, and at first I though C++'s operator overloads would help me out there.

Let's suppose I want to make an "augmented int" type, for instance, that can be treated just like a regular int, but allows for further action wherever I assign to it, and just assignment - all other properties of an int, such as adding with +=, should be preserved.

At first I first though that if I encapsulated the int inside some struct, and filled out the operator= overloads, I'd be set, like in the following example:

#include<iostream>

typedef struct PowerInt{
  int x;

  PowerInt(){
    cout << "PowerInt created\n";
    x = 0;
  }
  ~PowerInt(){
    cout << "PowerInt destroyed\n";
  }

  void operator=(int other){
    cout << "PowerInt received " << other << "\n";
    this->x = other;
  }
}PowerInt;

int main(){
  PowerInt a;
  a = 3;
  return 0;
}

The code compiles and runs as expected, but as soon as I try making anything else a regular int could do, like cout << a, or a += 2, or even a simple int b = a; assignment the compiler complains about the operators << and += missing.

Fair enough; I then though that, at least for << and "assigment =", I could get by using some sort of "generic rvalue operator", or some kind of method which returns PowerInt.x wherever my a is used as an rvalue, automatically making expressions like int c = (a + 3); and if (a == 3) {} valid.

Problem is, I can't find a way to implement this idiom, and this mostly likely has to do with either my little understanding of how operator overloading works in C++, or some language feature I'm not yet aware of. Is it possible to accomplish what I'm trying here?

MVittiS
  • 434
  • 3
  • 13
  • 1
    I don't see the relation to [rvalue](http://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues) – apple apple Sep 28 '16 at 09:11
  • There are some unnecessary C-isms here y'know – Lightness Races in Orbit Sep 28 '16 at 10:14
  • @LightnessRacesinOrbit You could point them to me, given that after programming in C for almost a decade I'm now just scratching C++'s surface, y'know. :) – MVittiS Sep 28 '16 at 10:48
  • 1
    `typedef struct T { } T;` .... just `struct T {};` will be fine. If you wanted to share your `struct` definition with C code then okay keep it compatible, but as this one has C++ class features you definitely aren't doing that. – Lightness Races in Orbit Sep 28 '16 at 11:13

1 Answers1

0

If you want your PowerInt to be convertible to a normal int you can create a user-defined conversion operator:

operator int() const
{
  return x;
}

Any operator that's not defined for PowerInt will then use the operator defined for a normal int.

P.S The typedef struct isn't necessary in C++.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122