views:

47

answers:

3

Hi,

In my program I have the following class hierarchy:

class Base // Base is an abstract class
{
};

class A : public Base
{
};

class B : public Base
{
};

I would like to do the following:

foo(const Base& one, const Base& two)
{
  if (one == two)
  {
    // Do something
  } else
  {
    // Do something else
  }
}

I have issues regarding the operator==() here. Of course comparing an instance A and an instance of B makes no sense but comparing two instances of Base should be possible. (You can't compare a Dog and a Cat however you can compare two Animals)

I would like the following results:

A == B => false

A == A => true or false, depending on the effective value of the two instances

B == B => true or false, depending on the effective value of the two instances

My question is: is this a good design/idea ? Is this even possible ? What functions should I write/overload ?

My apologies if the question is obviously stupid or easy, I have some serious fever right now and my thinking abilities are somewhat limited :/

Thank you.

+1  A: 

Overload the operator at the base: subclasses references will be casted to the base class reference.

Can't see any problem with the design - not without more context.

miquelramirez
Well the issue is that the `Base` class contains *no information or logic*. And If I use `dynamic_cast<>` in `Base::operator==()` I have to consider every possibility, which is not possible.
ereOn
So Base, rather than being an "abstract" class, is an "interface". If it's an interface - that is, you only have pure virtual methods - then operator== doesn't make any sense at all. What are you going to compare if Base objects do not have any state?
miquelramirez
+1  A: 
class Base // Base is an abstract class
{
    virtual bool equals(const Base& b) = 0;
};

class A : public Base
{
    virtual bool equals(const Base& base)
    {
        if (const A* a = dynamic_cast<const A*>(&base))
        {
            // Return true iff this and a are equal.
        }
        return false;
    }
};

class B : public Base
{
    virtual bool equals(const Base& base)
    {
        if (const B* b = dynamic_cast<const B*>(&base))
        {
            // Return true iff this and b are equal.
        }
        return false;
    }
};
Marcelo Cantos
I can't believe I didn't think about this... Thank you. I'll never code again when I'm sick.
ereOn
A: 

I can not craft a counterexample right now, but as far as I remember, the comparison operator (as something transitive, reflexive and symmetric) will always break (and be a source of malicious errors) when combined with inheritance. Possible it will not break you app, your use case, just half a year later when you subclass your subclass...

sibidiba