Reputation: 535
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;
}
Upvotes: 6
Views: 9847
Reputation:
You can't call a method on a member variable inside your class declaration.
In your cpp file you could do something like:
ChessBoard::ChessBoard() { pieces.resize(16); }
or:
ChessBoard::ChessBoard(): pieces(16) {}
The second one calls the vector constructor that takes a size argument. Or you can directly do it in your .h file:
class ChessBoard {
ChessBoard(): pieces(16) {} // version 1
ChessBoard(): pieces() { pieces.resize(16); } // version 2
private:
std::vector<ChessPiece *> pieces;
};
Upvotes: 7
Reputation: 227370
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);
Upvotes: 12