0

I am working on a chess game in C++, and each type of piece has its own class, which all inherit the "Space" class. For the board, I have an two dimensional 8x8 array of Space, declared as Space board[8][8] {} the brackets being filled with different instances of the piece classes.

I need to make an if statement to check if a space is empty. This means, I need to check a location on the array if it is empty. The current code for the if statement is

if(board[0][0] == wRook1 {}

Please note: wRook1 is an instance of the Rook class, which inherits the Space class. However, I get an error saying that the

operator == is not valid for the operands Space == Space.

How do I make the custom class Space work with the == operator?

Currently the Space class simply has a constructor, as it is only used to be an overarching type for the pieces.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Zuve
  • 19
  • 3

1 Answers1

1

The comparison operator can be virtual:

struct Base { virtual bool operator==(const Base &) const = 0; };

A typical implementation would check for type identity first, and then for object identity:

struct A : Base
{
    bool operator==(const Base & rhs) const override
    {
        if (auto * p = dynamic_cast<const A *>(&rhs))
        {
            return typeid(*p) == typeid(A) && /* compare value */;
        }
        return false;
    }

    // state
};

The inner type check is necessary to exclude the case where rhs is contained in an object derived from A rather than of type A exactly. You could spare yourself this extra check if A was final. You could alternatively start with the typeid check, but you generally still need the dynamic cast (rather than a static cast) in case the base is virtual.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084