C++ classes

Hello,
I've been having trouble understanding this code from the classes (2)section of the tutorials on this website:

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;
}


I don't understand why you do temp.x= x + param.x and temp.y= y + param.y. Any help would be great.
the class cVector has member variables x and y. the function you're referring to is overloading the '+' operator. the purpose of this is to be able to add 2 objects (instances/variables) of the class cVector

a temporary cVector object is created because you don't want to modify the calling object or the object that is accepted as an argument, you only want to return the sum of the two as defined by the overloading of the operator.

temp.x accesses the member variable x of the cVector object temp. temp.y for the member variable y. x and y by themselves don't have to be accessed using the dot operator because they refer to the member variables of the object calling the operator+() function. temp and param are other objects of the cVector class, but are not making the function call, so their member variables have to be accessed using the dot operator

if you look in the main function, you'll see c = a + b;. this is where the overloaded + operator is used. without the function, the compiler has no idea how to add two objects of type cVector.

let us know if this isn't clear

ps: another way to think of that line of code i quoted is to think of it like a function call like this:
c = a.operator+(b);
Last edited on
congrats, you used code tags on your first post =) thats rare >_> haha
Thanks for the help prophetjohn, i've been trying to figure this out for a couple of days.

Topic archived. No new replies allowed.