I want to return a Piece
from function. Piece
is an abstract class parent for all of my pieces.
Piece* Board::getPieceBySign(char sign, Player& _player1, Player& _player2, Player& _emptyPlayer, int row, int col) const
{
switch (sign) {
case Piece::B_KING:
// Example: King(Player& p, const int row, const int col, Board& b);
return new King(_player1, row, col, *this);
case Piece::B_QUEEN:
return new Queen(_player1, row, col, *this);
case Piece::B_ROOK:
return new Rook(_player1, row, col, *this);
case Piece::B_KNIGHT:
return new Knight(_player1, sign, row, col, *this);
case Piece::B_BISHOP:
return new Bishop(_player1, sign, row, col, *this);
case Piece::B_PAWN:
return new Pawn(_player1, sign, row, col, *this);
case Piece::W_KING:
return new King(_player2, sign, row, col, *this);
case Piece::W_QUEEN:
return new Queen(_player2, sign, row, col, *this);
case Piece::W_ROOK:
return new Rook(_player2, sign, row, col, *this);
case Piece::W_KNIGHT:
return new Knight(_player2, sign, row, col, *this);
case Piece::W_BISHOP:
return new Bishop(_player2, sign, row, col, *this);
case Piece::W_PAWN:
return new Pawn(_player2, sign, row, col, *this);
case Piece::EMPTY:
return nullptr;
}
}
In every line, I get an error that says the arguments are not as they should be. And it's not true. Maybe because I try to initialize memory inside of a switch
?
no instance of constructor matches the argument list
King.h
#pragma once
#include "Queen.h"
class King :
public Queen
{
public:
King(Player& p, const int row, const int col, Board& b);
bool isWayfree(const int destRow, const int destCol) const override;
bool isLeagalMove(const int destRow, const int destCol) const override;
};
CodePudding user response:
Piece* Board::getPieceBySign(char sign, Player& _player1,
Player& _player2, Player& _emptyPlayer, int row, int col) const
That trailing const
indicates that this is a const
method. In const
methods, the this
object is const
. That's what it means to be a const
method.
King(Player& p, const int row, const int col, Board& b);
*this
gets passed in as a last parameter to this constructor, however the parameter is a Board &
, and not a const Board &
. This is the reason for the compilation error. You either have to make that a const Board &b
, or getPieceBySign
must be a non-const
class method.
Now that you know the reason, you can go back and look at your compiler's full error message, including everything that follows the initial "no instance of constructor matches the argument list"; and you should be able to see that's exactly what your compiler is telling you, in its own way.