0

If I remove 'const' key word, I get error message from compiler(gcc-4.8.5).

But Is works fine in visual studio 2017.

It is very simple code just sorting the components of vector.

What's the meaning of const in this case??

And Why the error occured when I remove 'const'?

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class myClass
{
public:
    myClass() {}
    myClass(int _x ,int _y ,int _value) {
        x = _x;
        y = _y;
        value = _value;
    }
    int x;
    int y;
    int value;
    bool operator<(const myClass &v) const//If I remove this const I get error
    {
        if (value < v.value)return true;
        else return false;
    }
};

int main()
{
    std::vector<myClass>vec;

    vec.push_back(myClass(1, 0, 33));
    vec.push_back(myClass(1, 0, 3445));
    vec.push_back(myClass(0, 0, 1));
    vec.push_back(myClass(0, 1, 34));
    vec.push_back(myClass(0, 2, 32));
    vec.push_back(myClass(1, 0, 345));

    sort(vec.begin(),vec.end());
    for(int i=0;i<vec.size();i++)
    {
        std::cout << vec[i].x<<" "<<vec[i].y<<" "<<vec[i].value<<"\n";
    }
    return 0;
}
Wien 1683
  • 65
  • 6

1 Answers1

0

When it comes to operator overloading, you don't get a lot of flexibility wrt const-correctness. In the case of operator <, it's basically just a way of saying:

bool result = constVar1 < constVar2;

As in the left & right hand sides should remain unchanged during the comparison. The constness of the arguments is a direct consequence of the C++ specs in this case. Removing the const here allows for the operator to make unexpected changes to the object, which would break the usual behaviour of C++ operators.

robthebloke
  • 9,331
  • 9
  • 12