CPPDev
CPPDev

Reputation: 23

Problem with operator ==

I am facing some problem with use of operator == in the following c++ program.

#include < iostream>
using namespace std;

class A
{
    public:
        A(char *b)
        {
            a = b;
        }
        A(A &c)
        {
            a = c.a;
        }
        bool operator ==(A &other)
        {
            return strcmp(a, other.a);
        }
    private:
        char *a;
};


int main()
{
    A obj("test");
    A obj1("test1");

    if(obj1 == A("test1"))
    {
        cout<<"This is true"<<endl;
    }
}

What's wrong with if(obj1 == A("test1")) line ?? Any help is appreciated.

Upvotes: 1

Views: 386

Answers (4)

Mike Weller
Mike Weller

Reputation: 45598

strcmp returns 0 when the strings are equal, so you want:

return strcmp(a, other.a) == 0;

You should also use a const reference like Cătălin Pitiș says in his answer, because then you can use temporary objects with the operator, and you should also make the method itself const (since it doesn't modify the object) as Andreas Brinck says in the comments below. So your method should be:

bool operator ==(const A &other) const
{
        return strcmp(a, other.a) == 0;
}

Upvotes: 33

PierreBdR
PierreBdR

Reputation: 43244

Your error is that you create an instant value and pass it as reference to the operator== method. But your error is in your operator definition that should be:

bool operator==(const A& other) const

the body being the same.

Upvotes: -1

Simon Steele
Simon Steele

Reputation: 11608

It looks to me like you want this in your operator:

strcmp(a, other.a) == 0

strcmp returns 0 when strings match, and a number indicating whether the comparison is greater or less than otherwise.

Upvotes: 2

Cătălin Pitiș
Cătălin Pitiș

Reputation: 14341

bool operator ==( const A &other)

Use const reference, so a temporary object that is constructed in if statement can be used as parameter for operator==.

Upvotes: 3

Related Questions