-2

Why isn't the == operator getting properly overloaded (so that it can only return true)? I've tried without * but it does not help.

#include "stdafx.h"
#include <iostream>
    class alfa
    {
    public:
        int x;
        bool operator == (alfa  * &f)
        {
            return true;
        }   

    };

int _tmain(int argc, _TCHAR* argv[])
{
    //alfa alfa2;
    alfa * tab[2];
    tab[0] = new alfa;
    tab[1] = new alfa;
    if(tab[0] == tab[1])
    {
        std::cout << "tak";
    }

    scanf("%d");
}
zch
  • 14,931
  • 2
  • 41
  • 49

1 Answers1

4

Your operator is a member of alfa, so it could not accept two alfa pointers, but rather, an alpha instance on the LHS and a pointer to alpha on the RHS.

If you wanted an operator to accept two alpha pointers, you would have to make it a non-member:

class alfa
{
public:
    int x;
};

bool operator == (const alpha* lhs, const alfa* rhs)
{
    return true;
}   

However you are not allowed to overload comparison operators for built-in types such as pointers. You would have to provide an operator that can act on two instances:

bool operator == (const alpha& lhs, const alfa& rhs)
{
    return true;
}   

Then, given two alpha pointers a and b, you can compare them like this:

*a == *b;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 2
    Note that overloading == for pointers is a really bad idea. I think he wanted to compare objects. – zch Nov 09 '13 at 13:08
  • @zch It's not a bad idea, it's illegal. – john Nov 09 '13 at 13:10
  • @john Good point. I wasn't completely sure of there was an exception for pointers to user defined types, but I can't find any so I edited the answer. – juanchopanza Nov 09 '13 at 13:15