0
votes

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]|

1
#include <algorithm>, and make getName const. - BoBTFish
@BoBTFish: Please do not write answers in the comment section. We cannot peer review them properly. - Lightness Races in Orbit
@Lightness It's questionable if that question deserves an answer at all. - πάντα ῥεῖ
@πάνταῥεῖ: Well, it is an MCVE, at least. The "M" part could be stronger, but still. A very rare thing to see these days. - Christian Hackl
i tried to mock up a simple test because it is way too much code but in the original I did have #include <algorithm>. The real error is passing ‘const CLog’ as ‘this’ argument of ‘std::string CLog::GetName()’ discards qualifiers - flashc5

1 Answers

1
votes

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!