6

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;
}

2 Answers 2

12

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);
Sign up to request clarification or add additional context in comments.

Comments

7

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;
};

8 Comments

Your first ChessBoard constructor looks wrong. Maybe you mean ChessBoard(): pieces(16) {}?
@juanchopanza: Whoops, fixed. Thank you
I may be wrong but wouldn't pieces.resize(16) throw an error since the default constructor is inaccessible?
@IzaanSiddiqi: How is it inaccessible?
Sorry, I made a mistake somewhere else and it's working now. Thank you both for your help!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.