0
#include <iostream>

enum class Color { RED, GREEN };

Color& operator++(Color& source)
{
    switch (source)
    {
        case Color::RED:    return source = Color::GREEN;
        case Color::GREEN:  return source = Color::RED;
    }
}

int main()
{

   Color c1{ 1 };
   Color c2 = Color::RED;

   ++c1;  // OK
   std::cout << (int)c1 << std::endl;

   c2++;  // error
   std::cout << (int)c2 << std::endl;

   return 0;
}

I overloaded ++ operator but it only works from left hand side. What is the reason behind it?

Is it related to the way I do overloading or is it related to lvalue-rvalue concept?

arda30
  • 83
  • 1
  • 1
  • 6
  • 1
    I think there are different overloads for post increment and pre increment operators. See https://stackoverflow.com/q/15244094/4688321. – kiner_shah Nov 15 '21 at 11:13

1 Answers1

2

Color& operator++(Color& source) is for pre-incremant,

you need

Color operator++(Color& source, int) for post increment.

Jarod42
  • 203,559
  • 14
  • 181
  • 302