Re: Temporary objects and operators overloading
On 6 Jul., 05:15, cin <czec...@gmail.com> wrote:
Hi Guys,
Consider code below. I overloaded + and - operators for my class.
Theoretically everything looks fine but the code doesn't work as
expected. [...]
Is there any explanation for such behavior ?
Yes.
[...]
----- Overloading.h
class Overloading
{
int a;
public:
Overloading(int a);
Overloading& operator+(Overloading& arg);
Overloading& operator-(Overloading& arg);
};
operator+ and operator- should return a new object by value and take
their parameter(s) either by reference-to-const or by value. Also, it
is common to write operator+ and operator- in terms of += and -= as
free functions:
class Overloading {
[...]
Overloading& operator+=(Overloading const& rhs)
{
this->a += rhs.a;
return *this;
}
[...]
friend Overloading operator+(Overloading const& lhs,
Overloading const& rhs)
{
Overloading result = lhs;
result += rhs;
return result;
}
};
Since you have an implicit constructor taking an int you will be able
to write
void foo()
{
Overloading a = 23;
Overloading b = a + 42;
Overloading c = 99 + b;
}
without the need to declare more operator+ functions. 42 and 99 are
simply converted to Overloading and then operator+(Overloading const&,
Overloading const&) is applied.
--- Overloading.cpp
Overloading::Overloading(int arg = 0) : a(arg) {}
Overloading& Overloading::operator+(Overloading& arg) {
return Overloading(a + arg.a);
}
Your compiler should complain about this. You return a reference to
function-local object which ceases to exist. Using this dangling
reference invokes undefined behaviour.
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]