1

I'm trying to understand operators overloading, in the tutorial i use there is an example of overloading "+" operator for adding two objects.

  Box operator+(const Box& b)
  {
     Box box;
     box.length = this->length + b.length;
     box.breadth = this->breadth + b.breadth;
     box.height = this->height + b.height;
     return box;
  }

why does the parameter needs to be const reference to object?

Akka Jaworek
  • 1,970
  • 4
  • 21
  • 47

2 Answers2

10

The parameter is const because you don't need to modify the Box that was passed as argument.
The method itself should also be marked const, as it does not modify *this either.

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • so its just a precaution to not modify parameter correct? is it possible to override "+" operator without creating a temporary object within like this? ``this->length = this->length + b.length;`` and then ``return *this`` or would it cause some problems? – Akka Jaworek Apr 05 '16 at 18:21
  • @AkkaJaworek The binary `+` operator is generally expected to produce a new value from two operands, without modifying them. Nothing in the language stops you from doing it, but it would most probably be surprising to the users of the class. – Quentin Apr 05 '16 at 18:23
  • @AkkaJaworek _"is it possible to override "+" operator without creating a temporary object within like this?"_ Sure, just return `*this` as a reference then. – πάντα ῥεῖ Apr 05 '16 at 18:23
  • @Quentin It's the member operator overload in question. – πάντα ῥεῖ Apr 05 '16 at 18:24
  • @πάνταῥεῖ it still takes two operands (`*this` and `b`), as opposed to the unary `+` operator. – Quentin Apr 05 '16 at 18:26
0

To build on Quentin's answer, the most efficient way to pass in a "read-only" argument is to pass it in by reference or by means of a pointer (which are basically the same thing).

However, this may bring up a problem, because if the argument is modified within the function (it shouldn't, because you should be using it as "read-only", but if it is), then the original variable that was passed into the function is also modified. To prevent this, the parameter is marked as const.

This would not matter nearly as much if the "read-only" argument were not passed by reference or by pointer, but as I said before, it is much more efficient to do it this way.

Summary: The best way to pass in "read-only" paremeters is by const reference (&).

I hope this helps.

Fearnbuster
  • 806
  • 2
  • 14
  • 19