I have a class called ChessBoard and one of the member variables is
std::vector<ChessPiece *> pieces(16);
This is giving me an "expected a type specifier" error. The default constructor of ChessPiece is private. However, if I write the same statement inside a function it works perfectly (i.e. the initial size of pieces is 16). Why is it reporting an error when I try to specify initial size of a member variable? Thanks!
SSCCE:
class ChessPiece {
ChessPiece();
public:
ChessPiece(int value) { std::cout << value << std::endl; }
};
class ChessBoard {
ChessBoard();
std::vector<ChessPiece *> pieces(16); // Error: expected a type specifier
public:
ChessBoard(int value) { std::cout << value << std::endl; }
};
int main(int argc, char*argv[]) {
std::vector<ChessPiece *> pieces(16);
std::cout << pieces.size() << std::endl; // prints 16
std::cin.get();
return 0;
}
The required syntax for in-place initialization of data members does not allow the ()
initialization syntax common with non-members. You can use this syntax instead:
std::vector<ChessPiece*> pieces = std::vector<ChessPiece*>(16);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With