why put a reference in an "operator" when overloading an operand

Hello. I watched this lesson about function overloading(about increments) and I'm just wondering why he placed a reference before the "operator". What's the purpose of putting a reference in there? I thought a "reference" is used in data variables?
1
2
3
4
5
6
7
8
Mass &operator++(int)
	{
		Mass a = *this;
		a++;
		return a;
	}

Last edited on
The ampersand does not come before the operator keyword. It comes after the Mass identifier.

This example is identical:
1
2
3
4
5
6
7
8
using ReferenceToMass = Mass &;

ReferenceToMass operator++(int)
{
    Mass a = *this;
    a++; //infinite recursion
    return a; //dangling reference; possible crash/corruption later
}
The code is still incorrect, however.
Last edited on
First, know that what you have there is a very bad idea.

I'll get to that in a bit, but first explaining. Whenever you have the '&', you have a reference. What you are doing is saying that the return type is 'reference to Mass'. Therefore, rather than returning a copy of the object, you are returning the reference to the object.

Now, do you see the problem? a goes out of scope at line 6 - it will generally be cleaned from memory. However, you are also giving something a reference to that (now gone) object, which can be accessed or modified. Due to this, often your program will crash due to memory access violations.
Topic archived. No new replies allowed.