Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing objects and inheritance

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 ?

like image 265
ereOn Avatar asked Mar 09 '26 10:03

ereOn


1 Answers

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;
    }
};
like image 195
Marcelo Cantos Avatar answered Mar 11 '26 01:03

Marcelo Cantos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!