overloading operators...CONFUSING!!!!!!!

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

can some one help me understand this program. or you can also take another example to explain the concept Just my brain is not able to execute the instructions. so Please help me understandin this problem..thanks in advance:-)
What part do you have trouble understanding?
The code example should be pretty obvious if you've covered operator overloading.
It's pretty simple. Overloaded operators are just like functions but called differently. I got even simpler example class here. :P

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 Integer
{
public:
    Integer(int num)
    {
        number = num;
    }
    Integer()
    {
    }
    Integer operator+(Integer other)
    {
        Integer temp;
        temp.setNumber(this->getNumber() + other.getNumber());
        return temp;
    }
    int getNumber()
    {
        return number;
    }
    void setNumber(int num)
    {
        number = num;
    }

private:
    int number;
};
Here, I'll put it into words:

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

becomes

This is a CVector function with the + operator and one argument; another CVector named 'param'.
Lets declare another CVector (which we will return later) to be 'temp'.
This 'temp' will contain the sum of both CVectors x values for its x...
And the sum of both y values for its y.
Finally, we shall return temp, which now contains the sum of both vectors.


Breadman's example is the same, but with one argument and unnecisaraly simple functions.
closed account (1vRz3TCk)
guna8985,

I don't know if this will help or confuse you more, when you call the opperator with syntax such as c = a + b; it is equivalent to the following call c = a.operator+(b);.
Operator overloading is something unique in C++ and some developers like to call them syntactic sugar :P
i have this prob here is the thing i can read and understand it and probly even remember the syntax to re write it with diff arguments and so forth but i dont think if you asked me to write a program to do just that on my own based off that knowlage i could
I don't know if this will help or confuse you more, when you call the opperator with syntax such as c = a + b; it is equivalent to the following call c = a.operator+(b);.


helped
Last edited on
Topic archived. No new replies allowed.