Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Why this operator++ return a warning?

C++
Human& Human::operator++(int){
    Human temp(*this);
    operator++();
    return temp;    // warning here.
}


The warning is:
Reference to stack memory associated with local variable 'temp' returned.

There was no problem with the result except for the warning though.
What is the proper way to do it?
I'm learning about overloading.
I'm using XCode 7.1.1

another pair of the increment works without warning.
C++
Human& Human::operator++(){
    _health++ ;
    _attack++ ;
	_defense++;
    return *this;
}
Posted
Updated 8-Dec-15 0:22am
v2

1 solution

The local variable temp goes out of scope when the function returns and is no longer valid afterwards.

So you should return a value here rather a reference:
Human Human::operator++(int){
    Human temp(*this);
    operator++();
    return temp;
}


[EDIT]
See also here http://en.cppreference.com/w/cpp/language/operator_incdec[^] the Notes below the table:
Quote:
Prefix versions of the built-in operators return references and postfix versions return values

I suggest also to bookmark the above website en.cppreference.com (or a similar one) in your browser. It will be really helpful while trying out C++ features.
 
Share this answer
 
v2
Comments
Are Riff 8-Dec-15 6:36am    
Thanks.
Sergey Alexandrovich Kryukov 8-Dec-15 11:20am    
Right, a 5.
—SA
Are Riff 11-Dec-15 14:52pm    
thanks, I regularly read that website and cplusplus.com
It just sometime (or usually) they explaining something using too much technical words and I ended up needed to reread the same sentence more than twice to really get the meaning :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900