james
james

Reputation: 1035

Why the use of the first `&`?

I am reading "The C++ Programming Language by Bjarne Stroustrup" and came across this snipper of code:


1.  Traffic_light& operator++(Traffic_light &t){
2.      switch(t){
3.      case Traffic_light::green: return t = Traffic_light::yellow;
4.      case Traffic_light::yellow: return t = Traffic_light::red;
5.      case Traffic_light::red : return t = Traffic_light::green;
6.      }
7.  }

On line 1 the first part is Traffic_Light&, which signals that a reference to the enum class Traffic_light will be returned.

Okay being more specific: I realise the & used in front of a variable means "address of" and in this case it means a reference to an object. I understand why a reference is used in the parameter part of the function - this stops a local copy of the object being made and any changes are made to the passed argument. What confuses me is why a reference to Traffic_light needs to be returned as opposed to just an object?

Upvotes: 0

Views: 133

Answers (1)

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16017

The increment operator operates on a given object and should return a reference to that very object, not a copy of it. A copy would be created for the return value much like for a parameter if the first & was missing. As an example Traffic_light t = raffic_light::green; ++(++t); should increment the original t twice, which it wouldn't if a copy was returned (I think it wouldn't compile because the temporary returned by the inner increment would not be an lvalue).

Upvotes: 4

Related Questions