Suppose the following code:
struct Piece_t {
virtual ~Piece_t() = default;
std::string type;
};
struct Empty_t : Piece_t {
Empty_t() { };
bool run() { return false; };
};
struct Pawn_t : Piece_t {
Pawn_t() {
type = "Pawn";
}
bool move() {
return false;
}
};
struct Board_t {
using Cols = std::vector<Piece_t>;
using Board = std::vector<Cols>;
Board_t(size_t N = 8) : b{ Board(N, Cols(N, Empty_t())) } {
for (size_t i = 0; i < N; i++) {
b[1][i] = Pawn_t();
b[N - 2][i] = Pawn_t();
}
//more init's here...
}
Board b;
};
Here I have a Piece_t
, and Im creating a Board_t
, which has a std::vector<std::vector<Piece_t>>
.
Fair enough, however, now suppose that I want to add a pure virtual function to Piece_t
, like move
:
struct Piece_t {
virtual bool move() = 0;
virtual ~Piece_t() = default;
std::string type;
};
Doing this, however, is going to give me compilation errors, because I can not instantiate a std::vector<Piece_t>
like I do in Board
. This seems strange to me, because I'm actually doing an init with Empty_t
, and not with Piece_t
.
So here are my questions:
- Why is not letting me to compile the code with this modification? Suppose that I' have already implemented
move
in the other two structs. - What should be the correct pattern to create the desired behaviour? (Being creating a base class with a virtual pure funct. and later using that definition to getting advantage of polymorphism.