DenverCoder21
DenverCoder21

Reputation: 887

operator< overloading for std::set

This is my code:

#include <iostream>
#include <set>
#include <string>

class widget
{
public:
    widget(unsigned id) :
        m_id(id)
    {
    };

    ~widget(){};

    unsigned id(){ return m_id; };
    bool active(){ return m_active; };
    void set_active(bool active){ m_active = active; };

    friend bool operator<(const widget& lhs, const widget& rhs);

    bool operator<(const widget& rhs)
    {
        return m_id < rhs.m_id;
    }

private:
    unsigned m_id;
    bool m_active{false};
};

bool operator<(const widget& lhs, const widget& rhs)
{
    return lhs.m_id < rhs.m_id;
}

int main()
{  
    std::set<widget> widgets;

    widget foo(5);
    widget bar(2);

    widgets.insert(foo);
    widgets.insert(bar);

    for(const auto& hi : widgets)
        std::cout << hi.id() << std::endl;
}

On compiling I get the error: passing 'const widget' as 'this' argument of 'unsigned int widget::id()' discards qualifiers [-fpermissive]

And I don't understand whats happening. Am I doing the operator overloading wrong? Also, do I need the operator< as a member function with one parameter and as a free function with two parameters?

Upvotes: 0

Views: 1638

Answers (1)

Smeeheey
Smeeheey

Reputation: 10316

Add a const qualifier to your function id:

 unsigned id() const { return m_id; }

The reason is that in your loop, you iterate over your widgets set using a const reference - calling a non-const member function on this is forbidden.

Upvotes: 3

Related Questions