Sunday 24 July 2016

c++ - Operator overloading outside class




There are two ways to overload operators for a C++ class:




Inside class



class Vector2
{
public:
float x, y ;

Vector2 operator+( const Vector2 & other )
{

Vector2 ans ;
ans.x = x + other.x ;
ans.y = y + other.y ;
return ans ;
}
} ;


Outside class




class Vector2
{
public:
float x, y ;
} ;

Vector2 operator+( const Vector2& v1, const Vector2& v2 )
{
Vector2 ans ;
ans.x = v1.x + v2.x ;

ans.y = v1.y + v2.y ;
return ans ;
}


(Apparently in C# you can only use the "outside class" method.)



In C++, which way is more correct? Which is preferable?


Answer



The basic question is "Do you want conversions to be performed on the left-hand side parameter of an operator?". If yes, use a free function. If no, use a class member.




For example, for operator+() for strings, we want conversions to be performed so we can say things like:



string a = "bar";
string b = "foo" + a;


where a conversion is performed to turn the char * "foo" into an std::string. So, we make operator+() for strings into a free function.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...