0

I am trying to sort this class but for some reason I cannot get it to work. Can someone please tell me what I am doing wrong.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class CLog
{
public:
    string GetName()
    {
        return m_sName;
    }

    void SetName(string sName)
    {
        m_sName = sName;
    }
private:
    string m_sName = "";
};

bool sortByName(const CLog &lhs, const CLog &rhs)
{
    return lhs.GetName() < rhs.GetName();
}

int main()
{
    vector<CLog> lsLog;

    CLog oLog1;
    oLog1.SetName("b");
    lsLog.push_back(oLog1);

    CLog oLog2;
    oLog2.SetName("c");
    lsLog.push_back(oLog2);

    CLog oLog3;
    oLog3.SetName("a");
    lsLog.push_back(oLog3);


    sort(lsLog.begin(),
     lsLog.end(),
     sortByName
     );

    return 0;
}

This gives me these errors

25|error: passing ‘const CLog’ as ‘this’ argument of ‘std::string CLog::GetName()’ discards qualifiers [-fpermissive]|

25|error: passing ‘const CLog’ as ‘this’ argument of ‘std::string CLog::GetName()’ discards qualifiers [-fpermissive]|

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
flashc5
  • 307
  • 1
  • 6
  • 16

1 Answers1

1

This is a non-const member function:

string GetName()
{
    return m_sName;
}

That means it's deemed a function that "modifies" the object. We can see from the code that actually you didn't, but const-correctness doesn't care about that. You simply can't call such a function on a const CLog, or via a const CLog&, or via a const CLog*.

This is also a non-const member function, though it returns a const string:

const string GetName()
{
    return m_sName;
}

To make the member function itself const, you put the keyword at the end, like this:

string GetName() const
{
    return m_sName;
}

Now you can call the function on a const object, and if you try to write code inside the function that modifies the object, the compiler won't let you.

This should be explained in your C++ book. If it's not, get a better one!

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055