Overloading Operators

If I Overload the + operator in a Class A.
Now can I use the operator for regular addition?
Depends on what you mean exactly, but the answer is probably yes.
Yes ..i feel Athar is right .. u can use it for regular addition also ..as well as for the addition of two class objects ...
I meant:
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
class A
{
public:
     int x, y;
     A operator+ (A, B);
};

A A::operator+ (A, B)
{
     A c;
     c.x =  A.x + B.x;
     c.y = A.y + B.y;
     return c;
}

int main ()
{
     A X, Y, Z;
     int a, b, c;
     //Assuming I set some values to X, Y & b, c:
     Z = X + Y;
     //Upto here I know this is valid.
     a = b+c;
     //Will the above line be valid??
}


If it does, then another question:
If I create a second class B, and overload the + operator for it as well, How will the program know which operator to use if I use + in an operation?
Last edited on
If you have two functions,

plus (int a, int b) and

plus (float a, float b)

how does the program know which one to use?

If you have two separate classes, A and B, and both contain a function called drinkMe, like this:

1
2
3
4
5
classA someObject;
classB someOtherObject;

someObject.drinkMe();
someOtherObject.drinkMe();

how does the program know which drinkMe to use?

Is this too didactic?

Last edited on
So it will recognize them by their types?
And one final questions,
In what way should two classes be related so that one may be able to Add (using the overloaded operator) the Tow classes? Is it even possible?
1
2
3
4
5
6
7
8
9
class A
{
//Something
}

class B
{
//Something as well
}


Now what should be the relation between A & B so that:
A+B
Will be valid?
Now what should be the relation between A & B so that:
A+B
Will be valid?


1
2
A a;
B b;

Now the two following lines are equivalent:
1
2
a+b;
a.operator+(b);


This should answer your question.
Thanks for all the help!
Topic archived. No new replies allowed.