Unable to specify initial size of vector
c++, member, size, vector
Solution
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;
};
Problem
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; } ```