Niklas Niklas - 1 month ago 5
C++ Question

What does assignment operator means in return statements, like return t =...?

I have question, what does it mean to return an assignment expression like in my code example? I have an enum, and i have override the ++:operator. So it is possible to switch between ligths in my short example - but there is a part in the code i dont understand. The code compiles and work fine.

Code:

enum Traficlight
{green, yellow, red };

Traficlight& operator++(Traficlight& t)
{
switch (t)
{
case green: return t = Traficlight::yellow; //Here <--
case yellow: return t = Traficlight::red; //Here <--
case red: return t = Traficlight::green; //Here <--
default:
break;
}
}

int main()
{


Traficlight Trafic = Traficlight::green;
Trafic++;

if (Trafic == Traficlight::yellow)
{
cout << "Light is Yellow" << endl;
}

string in;

cin >> in;

}


What does the "return t = Traficlight::yellow" mean, why cant i just return
"Traficlight::yellow".

Answer

In the return instructions, the operator assigns to t which is a reference (modifies it) then returns the value.

That's what an incrementation operator does: modifies & returns reference at the same time so the incremented value can be used in another operation.

Comments