Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: passing 'const T' as 'this' argument of 'bool T::operator<(T)' discards qualifiers

#include <iostream>
#include <vector>
#include <algorithm>
class MyData
    {
    public:
        int m_iData;
        bool operator<(MyData rhs) { return m_iData < rhs.m_iData; }
    };

int main () 
{
    std:: vector <MyData> myvector(2, MyData() );
    myvector[0].m_iData=2; myvector[1].m_iData=4;

    std::sort(myvector.begin(), myvector.end()); 
}

Attempting to compile this gives:

error: passing 'const MyData' as 'this' argument of 'bool MyData::operator<(MyData)'
discards qualifiers
like image 967
Matt Munson Avatar asked Oct 23 '11 22:10

Matt Munson


1 Answers

The comparison operator will be called on a const-reference of a class instance, so it must be declared as a const member function.

It is also good practice to pass the argument by const-reference rather than by value, although it doesn't make much of a difference for your simple class:

bool operator<(const MyData & rhs) const { return m_iData < rhs.m_iData; }
//             ^^^^^^^^^^^^^^      ^^^^^
//             if you like         mandatory

It is generally highly recommended to declare all member functions constant which do not mutate your object. This does not only communicate your intention and design, but it would also not be possible otherwise to use those functions on constant objects or references.

like image 85
Kerrek SB Avatar answered Sep 22 '22 06:09

Kerrek SB