简体   繁体   中英

use “const” as parameter in operator overloading

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM