Search code examples
c++operatorsequals-operator

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.


Solution

  • 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==.