Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between overloading an operator inside or outside a class?

In C++, i know there are two ways to overload. We can overload it inside (like class a) or outside (like class b). But, the question is, is there any difference between these two either in compile time or runtime or not?

class a { public:     int x;     a operator+(a p) // operator is overloaded inside class     {         a temp;         temp.x = x;         temp.x = p.x;         return temp;     } };  class b { public:     friend b operator+(b, b);     int x; };  b operator+(b p1, b p2) // operator is overloaded outside class {     p1.x += p2.x;     return p1; } 
like image 526
Ali1S232 Avatar asked Apr 03 '11 22:04

Ali1S232


People also ask

What is the difference between overloading and operator overloading?

Operator overloading allows operators to have an extended meaning beyond their predefined operational meaning. Function overloading (method overloading) allows us to define a method in such a way that there are multiple ways to call it.

Which of the following operator can't be overloaded outside class in C++?

Explanation: . (dot) operator cannot be overloaded therefore the program gives error.

Can operator overloading done without class?

No. Operator overloading must involve at least one operand of class or enum type.


1 Answers

The member operator+ requires the LHS to be an a - The free operator requires LHS or RHS to be a b and the other side to be convertible to b

struct Foo {     Foo() {}     Foo(int) {}     Foo operator+(Foo const & R) { return Foo(); } };   struct Bar {     Bar() {}     Bar(int) {} };  Bar operator+(Bar const & L, Bar const & R) {     return Bar(); }   int main() {     Foo f;     f+1;  // Will work - the int converts to Foo     1+f;  // Won't work - no matching operator     Bar b;     b+1;  // Will work - the int converts to Bar     1+b;  // Will work, the int converts to a Bar for use in operator+  } 
like image 150
Erik Avatar answered Sep 21 '22 12:09

Erik