Overloading the ++ operator (prefix) help please

Hi all

For some reason (and I would really like to know exactly what that reason is ;)) my ++ operator overloading via a a friend function does not want to return the modified object back to the application.

Ok some code, first is the interface:

 
friend Player operator ++(const Player & p);


and the implementation:
1
2
3
4
5
6
7
8
9
10
Player operator ++(const Player & p)
{
	Player tempPlayer(p.name, p.team, p.level, p.points);
	tempPlayer.points = p.points + 1;

	if (tempPlayer.points % 100 == 0)
		tempPlayer.level = p.level + 1;

	return tempPlayer;
}


and i am calling it with a:
 
++ThePlayer


from inside main.cpp.

When I display all my member info before the call to ++ and then display all after the call they are the same...
Last edited on
Well, you aren't modifying the object the operator is called for, so it isn't surprising that nothing changes.
You're returning a temporary object (which you should only do for postfix ++), but you're not using it.
closed account (DSLq5Di1)
http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.14
Thanks all, busy learning this now for the first time and it can be a bit tricky.

I removed the temp object and the const so I am now working directly with object p and then returning it back and it works.

Sloppy9 thanks for the link, great site that. I bookmarked it for future reference.

Well problem solved.

1
2
3
4
5
6
7
8
9
Player operator ++(Player & p)
{
	p.points = p.points + 1;

	if (p.points % 100 == 0)
		p.level = p.level + 1;

	return p;
}
Last edited on
You shouldn't return a copy of the object, but the object itself.

1
2
3
4
5
Player& operator++(Player& p)
{
	if (++p.points%100==0)p.level++;
	return p;
}
Thanks Athar, I see what you mean. In mine the lack of the & after Player is responsible for a copy of the object being made right? Implemented your advice.
Topic archived. No new replies allowed.