c++operator-overloading

Overloaded "==" operator is not called when comparing pointers


I have a Task class which has a string text private member. I access the variable through const string getText() const;.

I want to overload the == operator to check if different instances of the object have the same text.

I've declared a public bool operator==( const Task text2 ) const; on the class header and code it like this:

bool Task::operator==( const Task text2 ) const {
     return strcmp( text.c_str(), text2.getText().c_str() ) == 0;
}

But it was always returning false even when the strings where equal.

So I added a cout call within the bool operator==( const Task text2 ) const; to check if it was being called, but got nothing.

It seems that my custom == operator is never being called.

My header:

#ifndef TASK_H
#define TASK_H

#include <iostream>

using namespace std;

    class Task {
        public:
            enum Status { COMPLETED, PENDIENT };
            Task(string text);
            ~Task();
            // SETTERS
            void setText(string text);
            void setStatus(Status status);
        // GETTERS
            const string getText() const;
            const bool getStatus() const;
            const int getID() const;
            const int getCount() const;
            // UTILS
            //serialize
            const void printFormatted() const;
            // OVERLOAD
            // = expression comparing text
            bool operator==( const Task &text2 ) const;
        private:
            void setID();
            static int count;
            int id;
            string text;
            Status status;
    };
    
    #endif

Edited the overload operation to use a reference, and got away from strcmp:

bool Task::operator==( const Task &text2 ) const {
    return this->text == text2.getText();
}

Main file:

using namespace std;

int main() {
    Task *t = new Task("Second task");
    Task *t2 = new Task("Second task");

    cout << "Total: " << t->getCount() << endl;
    t->printFormatted();
    t2->printFormatted();

    if( t == t2 ) {
        cout << "EQUAL" << endl;
    }
    else {
        cout << "DIFF" << endl;
    }

    return 0;
}

Solution

  • Task *t = new Task("Second task");
    Task *t2 = new Task("Second task");
    // ...
    if( t == t2 ) {
    

    You are not comparing Task objects, but pointers to Task objects. Pointer comparison is native to the language and compares identity of the objects (i.e. will yield true only if the two pointers refer to the same object or both are null).

    If you want to compare the objects you need to dereference the pointers:

    if( *t == *t2 ) {