Search code examples
c++structoperator-overloadingassignment-operator

Returning value of variable inside a struct when the struct is rvalue of an assignment


I have the following code:

class example {
   int x;
   inline void operator=(int value) { x = value; }
};

int main() {
   example foo { 100 };
   int bar = foo;
}

The int bar = foo; obviously doesn't work, because I'm trying to assign a variable of type example to a variable of type int.

Is it possible to retrieve the x variable without using a getter function and without using operator.? If so, is it still possible to do purely by code inside the struct, and keeping the int bar = foo; as is?


Solution

  • Add a conversion function to allow implicit conversion

    struct example {
       int x;
       inline void operator=(int value) { x = value; }
    
       operator int() const
       {
           return x;
       }
    };
    
    int main() {
       example foo { 100 };
       int bar = foo;
    }