Overloading operator+ with two arguments

Hello all,

Is it possible to overload the "+" operator in the following way?

(This is just a short example of what I'm getting at):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class MyClass {
    
    float f;
   
   public:
    
    MyClass() : f(0.0f) {}
    MyClass(float input) : f(input) {}

    MyClass& operator=(const MyClass& other) {
        if (this != &other) f = other.f;
        return *this;
    }

    MyClass& operator+(const MyClass& other) { 
        f += other.f; 
        return *this; 
    }

    friend MyClass operator+(int someInteger, MyClass& someClass);

};

MyClass operator+(int someInteger, MyClass& someClass) {

     return someClass + (float)someInteger;

} // possible?

int main() {

    MyClass mc(someValue);
    MyClass mc2();
    int i = 5;

    mc2 = mc + i;  // works fine
    mc2 = i + mc;  // cannot get this to work

    return 0;

}


...or do the objects both have to be of the same type always?

Last edited on
That certainly is possible. Only one of the objects has to be of the class type, the other can be of any type.

You have the right idea, you're just not specifying all the types you're trying.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class MyClass
{
  // stuff

  MyClass operator + (const MyClass& other) const
  {                   // member func, so '*this' is on the left of the +
    f += other.f;
    return *this;
  }

  MyClass operator + (int other) const
  {
    f += other;
    return *this;
  }   // repeat this for float, or whatever.  Or possibly even template it

};

// global funcs to put 'MyClass' on the right of the +, with something else
//   on the left

// these don't need to be friends, really, as long as you stick to public
//  stuff like ctors and the member versions of +

static MyClass operator + (int l,const MyClass& r)
{
  return MyClass(l)+r;
}   //  again, repeat with other types, or template 


edit: fixed minor goof
Last edited on
@jhrode: Be aware that your operator+ is very non-intuitive.

In the code:

int a = 5;
int b = 4;
int x = a + b;

x is assigned 9 by the third statement and a and b are unchanged.
In your operator+ above, you are actually modifying a such that
both x and a would contain 9.

Better is

1
2
3
4
5
friend MyClass operator+( const MyClass& lhs, const MyClass& rhs ) {
   MyClass result;
   // code here
   return result;
}


or

1
2
3
4
5
MyClass operator+( const MyClass& rhs ) const {
   MyClass result;
   // code here
   return result;
}

whoops -- I did that in my example too without realizing it. That's what I get for copypasta. Good catch.
Thanks guys - makes sense. Yeah, I realize the + operator was illogical - I think I must have had the "chaining" notion still stuck in my head, as in the assignment operator. Just a mistake of typing it out too quickly.
Topic archived. No new replies allowed.