Reputation: 3
I'm trying to write a function for the +=
operator of a C++ class which utilizes the already written +
operator function. So far, I have been unsuccessful in associating the this
pointer with the +
operator. These are some of the attempts I've made that compiled in g++
but did not produce the desired result. Twice I attempted simply to make a copy of the this
class, but that did not appear to work.
intstr& intstr::operator+=(const intstr& i)
{
intstr *a;
a = new intstr;
*a = *this + i;
return *a;
}
intstr& intstr::operator+=(const intstr& i)
{
intstr *a, b(*this);
a = new intstr;
*a = b + i;
return *a;
}
intstr& intstr::operator+=(const intstr& i)
{
intstr *a, *b;
a = new intstr;
b = this;
*a = *b + i;
return *a;
}
intstr& intstr::operator+=(const intstr& i)
{
intstr *a;
a = new intstr;
*a = this->operator+(i);
return *a;
}
In the test code, all I've done is replace the working line of code a = a + i
with a += i
, so I doubt the problem lies there, but it is possible. Is the only way to do this to copy the code from the +
operator into the +=
function?
Upvotes: 0
Views: 737
Reputation: 264551
Usually you do it the other way around:
intstr& intstr::operator+=(intstr const& rhs)
{
// Do this stuff to add rhs into this object.
return *this;
}
// Then + is implemented in terms of +=
intstr intstr::operator+(intstr const& rhs)
{
instr result(*this); // Make a copy as the result
result += rhs;
return result;
}
// Then your free functions as needed.
Upvotes: 0
Reputation: 311048
The operator can look like
intstr& intstr::operator+=( const intstr& i )
{
*this = *this + i;
return *this;
}
If the operator +
is declared as a class member function then you can also write
intstr& intstr::operator+=( const intstr& i )
{
*this = operator +( i ); // or *this = this->operator +( i );
return *this;
}
It would be a mistake to allocate dynamically an object of type intstr within the operator. At least there is no such a need to do this.
Upvotes: 1
Reputation: 208396
Usually the approach is the opposite: you implement operator+=
and then you implement operator+
using that implementation (create a copy of the first argument, then use +=
to increment by the second argument and return that).
Other than that, why are you calling new
in all versions? For operator+=
you don't need to create any new object at all. The operator should modify the value of the left-hand-side operand by incrementing it with the value of the right-hand-side. No new objects need to be created anywhere (and less so dynamically allocated with new
!)
Upvotes: 2