I am trying to learn how overloading operators works in C++. I managed to figure out how to implement the +=
and =
operators, but I am struggling with the +
operator. The compiler tells me that the operator can only take one or two arguments. I can't seem to figure out how to properly return the result.
The objects I can take as arguments would be the LHS and RHS of the operator, but it seems to me that I have to create a third instance of the class somehow to store and return the result. I don't think the +
operator is supposed to be modifying either the LHS or the RHS themselves.
Furthermore, creating a new instance within the method would not work, since that object would be removed after the method finishes.
So how do I properly store the result in a fresh instance?
This is what I tried so far:
#include <iostream>
class smallclass
{
public:
smallclass();
smallclass(int x);
smallclass& operator+=(smallclass&y);
smallclass& operator=(smallclass& y);
smallclass& operator+(smallclass& y);
int a;
};
smallclass::smallclass()
{
}
smallclass::smallclass(int x)
{
this->a = x;
}
smallclass& smallclass::operator+=(smallclass&y)
{
this->a += y.a;
return *this;
}
smallclass& smallclass::operator=(smallclass& y)
{
int value = y.a;
this->a = value;
return *this;
}
smallclass& smallclass::operator+(smallclass& y)
{
int value = y.a;
this->a += value;
return *this;
}
int main()
{
smallclass a = smallclass(5);
smallclass b = smallclass(6);
std::cout << a.a << std::endl;
std::cout << b.a << std::endl;
// a = 5
// b = 6
a += b;
std::cout << a.a << std::endl;
std::cout << b.a << std::endl;
// a = 11
// b = 6
a = b;
std::cout << a.a << std::endl;
std::cout << b.a << std::endl;
// a = 6
// b = 6
smallclass c;
c = a + b;
std::cout << a.a << std::endl;
std::cout << b.a << std::endl;
std::cout << c.a << std::endl;
// a = 12 should be 6
// b = 6
// c = 12
return 0;
}