Overloaded Operators

I was working my way through this websites tutorial and I reached the section on overloaded operators.

I can make the code work there is just one part I'm not understanding. Here is a modified example of the code from the tutorial.

My question is: What does the parameter.x portion actually do? Does it just iterate through until there are no more overloaded values? Parameter could have been any word, i changed that around and it works fine.

The output from the program is correct I just don't know why.

I can add as many CVector new values and it always comes out correct. I'm just not certain how the arithmetic processes step by step.

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

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

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

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

int main () {
  CVector a (3,1,3);
  CVector b (1,2,1);
  CVector c (3,1,3);
  CVector d;
  d = a + b + c;
  cout << d.x << "," << d.y << "," << d.z;
  return 0;
}
Last edited on
You are right about the word parameter. It can be any word. Some folks use rhs (right hand side). The Trolls at Qt use other, which I like.

In the your example statement adding the CVectors you have: d = a + b + c; which can be expressed as d = (a + b) + c;

a+b :
1
2
3
4
5
6
7
CVector CVector::operator+ (CVector rhs) {
  CVector temp;  // instantiate a temporary variable to hold result
  temp.x = x + rhs.x;  // the current object=a and rhs=b  so you have temp.x = 3 + 1
  temp.y = y + rhs.y;  // temp.y = 1 + 2
  temp.z = z + rhs.z;  //  temp.z = 3 + 1
  return (temp);
}


The function returns the temporary CVector and is called again with the current object=temp and rhs=c.
1
2
3
4
5
6
7
CVector CVector::operator+ (CVector rhs) {
  CVector temp;  // instantiate a temporary variable to hold result
  temp.x = x + rhs.x;  // the current object=temp (a+b) and rhs=c  so temp.x = 4 + 3
  temp.y = y + rhs.y;  // temp.y = 3 + 1
  temp.z = z + rhs.z;  //  temp.z = 4 + 3
  return (temp);
}


The function returns and the temporary CVector is assigned to CVector d.
Topic archived. No new replies allowed.