operator overloading in struct

Nov 6, 2010 at 11:38pm
I came across the following piece of code:

1
2
3
4
5
6
struct inter {
    int begin;
    inline bool operator < (const inter &o) const {
        return begin < o.begin;
    }
};


Two questions:

1) What's the second "const" doing here?

2) Why "const inter &o", not "const inter o"?
Nov 6, 2010 at 11:47pm
1) It's declaring the function as const. This "promises" that the function will not change the state of the object, and therefore allows you to call it on a const object.

Example:

1
2
3
4
5
const inter foo;  // two const objects
conar inter bar;

if(foo < bar)  // this would error if the < operator was not const
   //  because 'foo' is a const object 



2) It's passing by const reference, instead of by value. Passing by value creates a copy of the object, whereas passing by const reference doesn't.
Nov 7, 2010 at 1:20am
Would it be the same if I do

const inline bool operator < (const inter &o)

i.e. move the "const" to the beginning?

Also, what advantages does passing by const reference have?

Nov 7, 2010 at 1:51am
Would it be the same if I ... move the "const" to the beginning?


No. Because if you do that, the function is no longer const, and instead it returns a const bool.


Also, what advantages does passing by const reference have?


http://www.cplusplus.com/forum/articles/20193/

Basically:
advantage: avoids potentially expensive object copy
disadvantage: adds indirection when accessing data

The general rule is, basic types (int, char, etc) should be passed by value, and complex types (strings, vectors, user defined classes, etc) should be passed by const reference.

There are exceptions to that rule, of course, but it applies a large majority of the time.
Nov 8, 2010 at 5:17am
Thanks a lot, Disch! :)
Topic archived. No new replies allowed.