The direct equivalent of your Java equals
would be:
bool Dog::operator==(Dog d)
{
return Animal::operator==(d) && weight == d.weight;
}
But I'm not sure if this is what you really want. For starters,
you're taking the argument by copy, which means that your
comparing a copy. In particular, when you call
Animal::operator==
, you will pass a copy of the Animal
part
of Dog
, not the complete object. Class types are usually
passed by reference; reference to const if you don't want to
modify them. So the signature in the base would be something
like:
bool Animal::operator==( Animal const& other ) const
{
// ...
}
And similarly in Dog
. Also, the comparison operator in Dog
would probably take an Animal const&
, not a Dog const&
. (In
Java, equals
takes a java.lang.Object
, always.) Which means
that you'd have to verify that it was a Dog
:
bool Dog::operator==( Animal const& other ) const
{
return dynamic_cast<Dog const*>( &other ) != nullptr
&& Animal::operator==( other )
&& weight == other.weight;
}
EDIT:
As was pointed out in a comment, while this addresses the
immediate syntax issue raised by the original poster, it isn't
really the way we'd do this normally. The usual solution would
be something like:
class Animal
{
// If Animal is actually an abstract class (usually the case
// in real code), this would be a pure virtual.
// Derived classes overriding this function are guaranteed
// that other is actually of the same type as they are,
// so they can just static_cast it to their type.
virtual bool doIsEqual( Animal const& other ) const
{
return true;
}
public:
bool isEqual( Animal const& other )
{
return typeid( *this ) == typeid( other )
&& // ... his local conditions...
&& doIsEqual( other );
}
};
bool operator==( Animal const& lhs, Animal const& rhs )
{
return lhs.isEqual( rhs );
}
bool operator!=( Animal const& lhs, Animal const& rhs )
{
return !lhs.isEqual( rhs );
}
The implementation of operator==
and operator!=
can in fact
be done by inheriting from an appropriate class template, which
avoids some of the boilerplate if you have a lot of classes
which must support ==
and the others.