[Help] How to Initialize an Array in a Constructor

I am trying to initialize an array in my constructor and storing it in my char board[]. I am not sure how I can do this. I just want to initialize the value for board so i can replace it later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
    #include<limits>
    
    using namespace std;
    
    
    class TicTacToe {
    public:
    	void displayBoard();
    	void getMove();
    	void playGame();
        
        
        
    private:
    	char board[9];
    	char player; // Switch after each move.
    };
How do you want it initialized? If you want the entire board to have a default value, you could use memset() in the constructor:

1
2
3
4
5
public:
    TicTacToe()
    {
        memset(board, ' ', sizeof(board));
    }
Or #include <algorithm> and use fill() or fill_n().

1
2
3
4
    TicTacToe()
    {
        fill( board, board + 9, ' ' );
    }
closed account (DSLq5Di1)
1
2
3
public:
    TicTacToe() : board() {}; // Zero initialize
    TicTacToe() : board("12345678") {}; // This works but you need to leave room for an implicit null character 
Or declare board as such:

 
boost::value_initialized<char> board[ 9 ];

TicTacToe() : board("12345678") {};

is not valid as far as Visual C++ 2008 is concerned.

error C2536: 'TicTacToe::TicTacToe::board' : cannot specify explicit initializer for arrays

Is it valid for C++0x?

[code]TicTacToe() : board() {}; // Zero initialize[code]

Is OK with modern compilers. But some older ones might not handle this.

Visual C++ 2008 tells me:

warning C4351: new behavior: elements of array 'TicTacToe::board' will be default initialized

I still use memset(), or the WIN32 equiv ZeroMemory(), out of habit. Which I should really get out of!
Last edited on
closed account (DSLq5Di1)
VS 2010 here, I tried the 2nd initialization on a whim, and to my surprise it worked. I suspect when raw literals are introduced this might be a more viable initialization.. though by then we would hopefully have support for initializer lists. (GCC already does I think?)

Old habits die hard hehe. ^^
I tried gcc 4.4 and it didn't like the array initialization.

But I haven't tried the newer gcc releases yet (latest is 4.6.1, with 4.7 under development)
Topic archived. No new replies allowed.