Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

overloading (+) HELP

0 views
Skip to first unread message

Maya

unread,
Dec 30, 2002, 1:41:16 PM12/30/02
to
I am writing a class that overloads the addition operator (+) as follows:

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

Strange

unread,
Dec 31, 2002, 3:53:38 AM12/31/02
to
Maya <esca...@canada.com> wrote in message news:<pan.2002.12.30.2...@canada.com>...

> I am writing a class that overloads the addition operator (+) as follows:
>
> 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

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).

Peter Koch Larsen

unread,
Dec 31, 2002, 8:12:08 AM12/31/02
to
Maya <esca...@canada.com> wrote in message news:<pan.2002.12.30.2...@canada.com>...

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;
}
)

Josh Sebastian

unread,
Dec 31, 2002, 9:16:36 AM12/31/02
to
On Mon, 30 Dec 2002 20:41:16 +0200, Maya <esca...@canada.com> wrote:

>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

0 new messages