overload operators

i have tried a different source for learning about overload operators and special uses and came across this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  // sample of Operator Overloading

#include <string>

class PlMessageHeader
{
    std::string m_ThreadSender;
    std::string m_ThreadReceiver;

    //return true if the messages are equal, false otherwise
    inline bool operator == (const PlMessageHeader &b) const
    {
        return ( (b.m_ThreadSender==m_ThreadSender) &&
                (b.m_ThreadReceiver==m_ThreadReceiver) );
    }

    //return true if the message is for name
    inline bool isFor (const std::string &name) const
    {
        return (m_ThreadReceiver==name);
    }

    //return true if the message is for name
    inline bool isFor (const char *name) const
    {
        return (m_ThreadReceiver==name);// since name type is std::string, it becomes unsafe if name == NULL
    }
};


now i know what the code does but i'm confused by the const at the end of the overload operator declaration and function declaration and cant seem to understand why the argument inside the overload operator and function declaration is a constant, cant it be just as it is without const ? (i know what const does but cant understand why its needed where it is in the sample code + i know that functions inside of the class are declared as inline by the compiler and it is unneeded to declare them as inline like in the sample).
i know what const does but cant understand why its needed

There is a contradiction. You "know", but don't "know".

First, recall what you know about const.

Then read https://isocpp.org/wiki/faq/const-correctness
(Particularly the "const member function".)
cant it be just as it is without const ?
Yes, but then you can only compare non const objects of the type PlMessageHeader.


1
2
3
4
5
6
7
const PlMessageHeader h1;
PlMessageHeader h2;

if(h1 == h2) // Compiler Error
{
...
}
Topic archived. No new replies allowed.