tags:

views:

260

answers:

8

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); 
}
+6  A: 

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 += .

agsamek
Thanks, this helps a lot. I was struggling with this concept for a fews days. Guess I just haven't gotten enough sleep. Now it makes total sense.
Brundle
-1 from me for discouraging the use of `const`. Using `const` is, IMO, one of the most powerful tools in a C++ programmer's toolbox, while at the same time being one you are very unlikely to hurt yourself with. It's one of the greatest features of the language and its use should be encouraged wherever possible.
sbi
discouraging? Interesting interpretation. -1 ? Even more interesting.
agsamek
discouraging const/encouraging to use the non-const version... that is a horrible advice. Semantically `a+b` should not modify neither `a` nor `b`, so it makes the most sense to have it `const`. I found interesting the last edit you did (implement `+` in terms of `+=`, but still miss suggesting `+` to be implemented as a free function regardless of the presence of `+=`)
David Rodríguez - dribeas
I hope you like this version better.
agsamek
@sbi: Const is goddamn annoying. I spend more time crapping around marking things const when they never need to be than any benefit const could ever give. I'd be much happier if const never existed. In addition, there's no sense or value in returning a const rvalue.
DeadMG
@DeadMG returning a const prevents code like `Person a,b,c; (a+b) = c;`, so it's not completely nonsensical, but it is rather unlikely than anyone would make the sorts of error it prevents.
Pete Kirkham
No, that's illegal even with non-const rvalues. `int a, b, c; (a + b) = c;` is an error. The left-hand of operator= must be an lvalue.
DeadMG
@DeadMG: Pete's code is not forbidden, yours is. For UDT's you can invoke non-`const` functions on rvalues, which includes calling the assignment operator. Assignment to rvalues of built-ins is forbidden.
sbi
@DeadMG: More than a decade ago, when I had joined a new company and was assigned to a project, I found that I couldn't call some member function from my `const`-correct code because someone had forgotten to make it `const`. So I went in and made it `const` - just to discover that it called three other functions two of which were missing a `const`. So I went in... I had my new co-workers laughing at me while I hunted through a several-10kLoC codebase and added `const` - until I showed them some of the very embarrassing errors the compiler had found me with the help of `const`. Incidentally...
sbi
...a few hard to reproduce bugs that nobody ever had even tried to find were gone afterwards. In a meeting it was then decided that developers are to add `const` wherever and whenever possible. The moral of this? __Never underestimate `const`.__
sbi
@sbi: I guess it's true that I mostly code for myself instead of in such an environment. I still think that it could use a greater degree of automation - for example, automatically labelling functions const when appropriate. Edit: Distinctions between UDTs and primitives is phail. I thought C++ ditched all of those.
DeadMG
@agsamek: FWIW, after your edit, I removed my down-vote.
sbi
@sbi - thx, I was wondering whether you remember about this detail ;)
agsamek
+2  A: 

Here is an example for a working += in a class.

Vector3D& operator+=( const Vector3D& other ) {
        x+=other.x;
        y+=other.y;
        z+=other.z;
        return *this;
    }
InsertNickHere
You wouldn't want to take a vector by copy.
sbi
I wanted to show how he gets a working += . This version works, but ok, now its a reference to make ppl happy.
InsertNickHere
@InsertNickHere: (You should properly attribute comments directed at someone, otherwise they don't show up in their list of responses and are likely to be overseen.) Good, I have removed my down-vote. Note that, when you answer a question, you usually are effectively teaching someone to do something they don't know how to do. If you omit something you don't think is relevant to the answer, they won't learn to regard it.
sbi
@sbi Ok, I will take this into account when writing my next answer.
InsertNickHere
A: 

Seems you made the member operator+ declaration with no intent to reference any Person-instance data: the member operator, as any member method, accepts the instance on which it is invoked as an argument.

If for some reason you need to make it a member (e.g., access to private state), you can declare it static.

Ofek Shilon
+6  A: 
sbi
+1  A: 
 class Person
  {
    private:
     int age;
     double weight;
    public:
      Person();                           //default constructor       
      ~Person();                           // destructor
      Person operator+(const Person &r); //overloaded operator as member function, so only one argument is required to be passed
 };

Implementation :

  Person Person::operator+(const Person &r)
  {
      Person x;
      x.age=this->age + r.age; // this refers to the object on which the function has been invoked, P1 in this case(see below)
      return x;
  }

When you overload a binary operator(+ in this case) as member function, the object on which the operator is invoked is passed implicitly to the function and you need to pass only one argument explicitly

Thus your main function should be like this

 int main()
 {
    Person P1,P2;
    P2=P1+P2; //P1 is passed implicitly 

    //The above expression is equivalent to P2=P1.operator+(P2);
}
Satish
-1: `operator+` is not supposed to modify `this`. If you made it `const`, the compiler would have caught your mistake.
Job
@Job: Thanks for pointing that out. Mine was a trivial implementation though. Now could you please remove your downvote?
Satish
@Satish: Sure I will. There is still a small error, though: it should be `Person Person::operator+`.
Job
+1  A: 

From what I've read the best practice is to declare operator+ as a friend function and not as a member function.

There's a whole discussion of this issue over at cplusplus.com:

Binary operators as friends - why?

Meyers also discusses it in his book Effective C++ IIRC.

Quoting from the comment of geustgulkan:

For any given binary operator, it the left hand object that carries out the operation.

Say we have a class ClassX which has an overload for the + operator for integers. Then if we create an object of thet class (call it objx), then we can say objx + 2. objx will will carry out the operation and return the result object of ClassX.

But what happens if we say 2 + objx ? The result should be the same as 2 + objx - BUT integers are not classes and certainly numeric literals are not - so 2+objx is not possible directly.

It would be a pain if we had to design our code to make sure we always has ojbjects of ClassX on the left hand side of the + whenever we wanted to add an int to it.

This is where we use friend overloads for operator+ for ClassX.

class ClassX
{

    friend ClassX operator+(ClassX objx, int i);
    friend ClassX operator+(int i, ClassX objx);
};

So what you probably want is:

class Person
{
private:
    int age;
    double weight;
public:
    Person::Person();                           //default constructor       
    Person::~Person();                           //default desctructor
    friend Person operator+(const Person &rhs, const Person &lhs);
};

Person operator+(const Person &lhs, const Person &rhs) {
     // do whatever constitutes addition here
     Person temp = lhs;
     temp.weight += rhs.weight;
     return temp;  // return copy of temp
}
Robert S. Barnes
Job
@Job: Sorry, wasn't paying attention - fixed it.
Robert S. Barnes
+1  A: 

I only have one advise: use Boost.Operators.

class Person: boost::addable<Person>      // yes private inheritance
{
public:
  Person& operator+=(Person const& rhs);

private:
};

There are 2 advantages as far as I can see:

  • No need to write boiler-plate code, and thus no chance to get it wrong ;)
  • Make for a clear interface, addable is pretty much self-explanatory

Boost.Operators provides a reference table, which for each behavior lists the required operators that should be defined and those that will be generated automatically.

It's very handy to keep the interface compact and to inject some documentation right into the code.

Matthieu M.
A: 

Hello, I agree with argumentations of agsamek and sbi. I add some extra considerations

  1. as you can see your class Person doesn't have any costructor with 2 arguments and that's an error (but not yet signaled by compiler)
  2. ofen when you overload one math operator you need also to overload the "operator=" and the constructor;
  3. if you want to overload the plus operator with 2 arguments you can't use an instance member but you must use a function. I avoid to declare friend functions because you break encapsulation of that class (it will be more difficult to maintain). It's better to implement some "accessor methods" to get object's internal values;
  4. in some compilers, an inline method needs declaration and definition in the same place (normally in .h file) so in less manutenable. Moreover the expansion of that code is at compiler discrection.

Next follow my solution to your question:

class Person
{
private:
    int age;
    double weight;
public:
    Person(){}                           //default constructor       
    Person(int a, double w) : age(a), weight(w) {}
    ~Person(){}                           //default desctructor

    int getAge() const { return age; }
    double getWeight() const { return weight; }

    const Person & operator =(const Person & rha) {
        age = rha.age; weight = rha.weight; return *this;
    }
};

Person operator +(const Person & lha, const Person & rha)
{
    return Person(lha.getAge() + rha.getAge(), rha.getWeight() + lha.getAge());
}

int _tmain(int argc, _TCHAR* argv[])
{
    Person p1(30,75);
    Person p2(40,80);

    Person sumOfPis = p1 + p2;  // <-- Without "operator =" this statement will use the default copy constructor

    return 0;
}
cesare augusto