Question with the operator overloading

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
// vectors: overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int,int);
    CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
  x = a;
  y = b;
}

CVector CVector::operator+ (CVector param) {
  CVector temp;
  temp.x = x + param.x; 
  temp.y = y + param.y;
  return (temp);
}

int main () {
  CVector a (3,1);
  CVector b (1,2);
  CVector c;
  c = a + b;
  cout << c.x << "," << c.y;
  return 0;
}


The above code is given in one of the tutorial in this website.
In the operator overloading function, in the line
temp.x = x + param.x;
As I notice x is assigned 3 and param.x is assigned 1.
But my doubt is that nowhere in the program, the param has not been assigned anything, then how would compiler interpreted that param.x=1 ?
Last edited on
When you call
c = a + b;

This calls your
CVector CVector::operator+ (CVector param)

a is the class that is performing the operation and b is inserted into this function as the argument param.

Therefore, param.x is 1.

The function outputs the temp class. In main this is sort of like replacing a+b with a class containing the values of temp. c gets this value.
Last edited on
I guess you are referring to the operator+ definition.

Well param is the argument of this function as @Stewbond mentioned.

Assignment of these values has been performed here:
1
2
  CVector a (3,1);
  CVector b (1,2);


So when operator+ is called argument to this function is b which has the values previously assigned.

It's basically the same as a function taking some built in type like int as argument. Here instead is CVector.

I guess the problem is imagining this operator as function with argument and a invoking object. If it helps c = a + b; is the same as invoking:
c = a.operator+(b);

You can work with either of the two versions but as you can imagine noone is working with the second one (it's more intuitive and simple to use the first form)

One last thing, in this implementation b is copied when this operator is invoked. It would be just fine to use reference not to copy it.
Last edited on
Thank you @stewbond and @eypos.. Now My doubt got cleared !!
Topic archived. No new replies allowed.