Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to specify initial size of vector

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;
}
like image 294
Izaan Avatar asked Jul 15 '14 21:07

Izaan


1 Answers

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);
like image 196
juanchopanza Avatar answered Sep 22 '22 08:09

juanchopanza