Operator overloading in C++ - why do we need to pass parameter as const & (…)?

let's say I want to overload an operator ==. I've got a class vector and the following method:

bool operator ==( const Vector & v )
    if(( this->x == v.x ) &&( this->y == v.y ) )
         return true;
         return false;


Why do I need to pass an object (in this example v) as a constant address to this object? I know - const to force the programmer not to modify the passed object, but why &?

My second question concerns an operator overloading like +=, *= etc. Please, look at this code:

Vector operator +( const Vector & v )
    return Vector( this->x + v.x, this->y + v.y );

// vs
Vector & operator +=( const Vector & v )
    this->x += v.x;
    this->y += v.y;
    return * this;

In the second case we can return a new object as well. Why do we return the same, incremented object?


You don't have to do that, it's just desirable to avoid needlessly copying an object.

For your second question, again you don't have to do that, but it makes += operate similarly for Vector as it does for int or double

Need Your Help

Calling a procedure with objects as arguments


Trying to save code. I want to display text etc on an image on the form at OnActivate then print the same text on clicking button (Real program is more complicated). To save writing code twice I ...

Why does setting a property on an enumerated object not work?

c# ienumerable

I know a lot about C# but this one is stumping me and Google isn't helping.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.