Pergunta

I try to have an operator== called from a derived class

but if i use base class pointers, it does not work, although the objects are created as derived classes

class A 
{
public:
    bool operator==(const A & other)
    {
        cout << "this should never been called" << endl;
        return this==&other;
    }
};

class B : public A
{
public:
    bool operator==(const A & other)
    {
        cout << "this should be called instead" << endl;
        return this==&other;
    }
};

void process(A _b1,A _b2)
{
    if(_b1==_b2)
    {
       cout << "here" << endl;
    }
}

int main() 
{
   B b1;
   B b2;

   process(b1,b2);
}

although the operators overload have the same signature, i dont get it

plz help me out

thx

Foi útil?

Solução

First, the bool operator==() in the class A should be virtual. Like:

class A 
{
public:
    virtual bool operator==(const A& other) { ... }
};

That means that even if you refer to a class A, it can be treated as B, if that is what it really is.

Second, you make a copy of your B instances to A instances. That is a conversion you do not want. Instead you should pass them "by reference". Like this:

void process(A& _b1,A& _b2)
{
    ...
}

That way, when they are actually processed, they still refer to the original objects, which are of class B.

Outras dicas

The problem is void process(A _b1,A _b2), it makes an implicit conversion/upcasting of the B class in A class, so it is called the A operator==, you should change your code to support polymorphism:

class A 
{
public:
    virtual bool operator==(const A & other)
    {
        cout << "this should never been called" << endl;
        return this==&other;
    }
};

class B : public A
{
public:
    virtual bool operator==(const A & other)
    {
        cout << "this should be called instead" << endl;
        return this==&other;
    }
};

void process(A& _b1,A& _b2)
{
    if(_b1==_b2)
    {
       cout << "here" << endl;
    }
}

int main() 
{
   B b1;
   B b2;

   process(b1,b2);
}

Ciao Angelo

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top