0

I found a piece of code online. But I don't understand what does the second const do in the operator function:

class Node {
public: 
    int row, col, val;
    Node (int r, int c, int v) : row(r), col(c), val(v) {};
    bool operator < (const Node &obj) const {
        return val > obj.val;
    }
};

Can anyone explain its purpose? Thank you!

Ting Wang
  • 221
  • 3
  • 13
  • 1
    It makes the function itself `const`, members of Node from the owning object may not be modified (that doesn't include `static` members or members from another object of `Node`). The `const` is also just a programmers promise, it can technically be cast away, though there's almost never a situation for that. – George Nov 24 '19 at 23:45

1 Answers1

1
bool operator < (const Node &obj) const {
  • First const means obj is passed by const reference. That means obj is not expected to be changed within this operator < function.

  • Second const means this is a const member function. That means operator < function does not change the state of the object itself (including all its data members: row, col, val).

Both const are measures for the compiler to catch unexpected changes (bugs): either changes to the parameter or to the object state itself.

artm
  • 17,291
  • 6
  • 38
  • 54
  • Thanks! One more question, why it's ```val > obj.val```, why not ```val < obj.val```, when overriding the ```operator <```? It really confuses me. – Ting Wang Nov 25 '19 at 00:01
  • @TingWang it could probably a typo in your original code. From normal convention, yes, it should be `val < obj.val` – artm Nov 25 '19 at 00:11