jme::Money& jme::Money::operator+(const jme::Money& par){
jme::Money tmp;
tmp.setAmount( amount + par.getAmount() );
return (tmp);
}
However, when compiling, I get a warning saying:
reference to local variable `tmp' returned
Later, the program compiles but throws a segmentation fault.
Can anybody tell me what I am doing wrong and how to fix this problem?
TIA
You can't return a reference to a local variable. A reference is
essentially a pointer. You can't return a pointer to tmp because tmp
will be out of scope the moment your function ends. Hence when the
caller tries to use the pointer (or reference in your case), the
program crashes.
Instead of returning "jme:Money&", return "jme:Money". Note: no "&".
But be aware that this creates a new object, which means it may be
inefficient. Your copy ctor must be defined properly too (or the
default one must work).
If a compiler emits a warning, You should either correct the code or
(if possible and the warning is irrelevant) hide it.
In this case, the warning has relevance. Your + operator returns a
reference (practically speaking: a pointer) to an area of mermory,
which at the return-point is unusable. You should return a value
instead:
jme::Money jme::Money::operator+(const jme::Money& par)
Also, standard practice is to make operator+ a friend function while
keeping operator += a memberfunction:
jme::Money operator+(const jme::Money& lhs,const jme::Money& rhs)
{
jme::Money res(lhs);
res += rhs;
return res;
}
(where you have defined this function in your class
jme::Money& jme::Money::operator+(const jme::Money& par)
{
jme::Money tmp;
setAmount( amount + par.getAmount() );
return *this;
}
)
>Newsgroups: comp.lang.c++,gnu.g++.help,alt.comp.lang.learn.c-c++,linux.dev.gcc
>Followup-To: gnu.g++.help
Please stop cross-posting to multiple groups and then setting
followups to one group without saying anything about it. That's *very*
rude.
Josh