Brundle Brundle - 1 month ago 16
C++ Question

C++: overloading mathematical operators

I am looking to overload, let's say, the addition operator and have it add two objects of the same class. When I declare this "operator+" prototype function in the class declaration in the header file, I pass in both objects as parameters. I get a compiler error saying that "binary 'operator +' has too many parameters". I was searching around for an answer online and found out that declaring an inline function just outside the class declaration in the header file compiled out. I'm wondering what I was doing wrong or if I'm missing something here. Here is the code I am using in the header file.

class Person
{
private:
int age;
double weight;
public:
Person::Person(); //default constructor
Person::~Person(); //default desctructor
Person operator+(Person r, Person i);
};


This compiles with the error I mentioned above. Below is the code that compiles fine.

class Person
{
private:
int age;
double weight;
public:
Person::Person(); //default constructor
Person::~Person(); //default desctructor
};
inline Person operator+(Person r, Person i)
{
return Person(0,0);
}

Answer

If you declare oparator+ as an instance function then the first argument is being passed as this object and thus you need only one more argument. Read this for more info, in particular try to understand the const concept:

http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html

The best approach as advised in the referenced artice is:

class Person
{
    ...
    Person &operator+=(const Person &i);
    const Person operator+(const Person &i) const;
    ...
};

Person &Person::operator+=(const Person &i) {
    ...   // Do the compound assignment work.
    return *this;
}

const Person Person::operator+(const Person &i) const {    
    Person result = *this;     // Make a copy of myself.  Same as MyClass result(*this);
    result += i;            // Use += to add other to the copy.
    return result;              // All done!
}

if you decide to use const version remember that you will only be able to call const methods on this and i references. This is the preferred way.

The article I referenced to explains the idea of overloading += first and then defining + using += in more details. This is a good idea since += operator must be separately overloaded.

Additionally - David Rodríguez suggests operator+ to be implemented as a free function regardless of the presence of += .