Advertisement

Operator Overloading?????

Started by May 13, 2002 02:07 PM
4 comments, last by Nouman 22 years, 9 months ago
I need some info on operator overloading..... Lets say that I have a class A, why Can''t I define a member function of Class A to overload a binary operator which has an object of class B as its left operand??
I think I get what your saying..

It would need to be a friend function

friend ??? operator &binaryop&( A&, B& );


you then implement outside of the class, don''t use the classes scope res

A:: <-- no.

Advertisement
no its not like that
I want to use a member function of class A to overload a binary operator'+' where its left operand is not an object of class A

class A{
public:
void operator+(const B&, const A&);

-----
-----
}
where B is another class.

and use it like

objectB+objectA


[edited by - nouman on May 13, 2002 3:45:11 PM]
b/c then it should be a member function of classB. you define the + operator for whatever class appears immediately to the left of the + sign in your expression. i think it's a class ownership issue. my understanding is that the compilation of + looks to the left and sees if the class to it's left has an overloaded operator.

i.e. it's just a product of the way ownership of the + operator is defined.

so just overload the operator in class a like:

class B{public:   ResultClass operator+(const A&);----------}  


-me

[edited by - Palidine on May 13, 2002 3:51:56 PM]
palidine, I know that we have to declare the operator member function in the class whose object is the left operrand of the operator. but my question is y is it that way??? y can''t we declare the operator member function in the class whose object is the right operrand of the operator????

I think now I have made myself pretty clear.
Nouman the way you''re declaring the operator is not valid. If you overload an operator as a class member you have two options:

1 - make it a static function and explicitly list both operands as arguments

1 - make it non-static and explicitly list only the right operand, the left operand is accessed via the this pointer

Further, a binary operator doesn''t have to be a member of either the lhs or the rhs class, and I''d say if they''re different types it probably shouldn''t be a member of either for reasons of clarity.

This topic is closed to new replies.

Advertisement