Search code examples
c++operatorsoverloading

How to overload == operator?


I'm using QT to design an app and I can't overload == for a class. Equals works perfectly but == doesn't work and I can't figure out why.

Here is my code:

  class connection{
        public:
            connection(State* s, Transition* t);
            connection(Transition* t, State* s);
            State* state;
            Transition* transition;
            bool equals (const connection* c) const; //edited, i missed const in copy paste
            bool operator==(const connection &c) const;
        };
        bool connection::equals(const connection* c) const{ 
            if (state->objectName() == c->state->objectName() && transition->objectName() == c->transition->objectName()){
                return true;
            }
        return false;
        }  

        bool connection::operator==(const connection &c) const{
            if (this->state->objectName() == c.state->objectName() && this->transition->objectName() == c.transition->objectName()){
                return true;
            }
        return false;
    }


// and when i try to compare...
       if (c->equals(d)) // works perfectly
       if (c == d)  // always return false

Solution

  • if(*c == *d) // works perfectly
    

    derefence operator.