#### Archived

This topic is now archived and is closed to further replies.

# Initializing An array in a class.

## Recommended Posts

Quiggy    122
I''m trying to do something really simple. Just setting up a game board. Here''s what I have so far.
#pragma once

class CGameData
{
private:
char GameBoard[] = {'' '', ''|'', '' '', ''|'', '' ''};

public:
CGameData(void);
~CGameData(void);
};

When I compile, it complains at my array init statement saying ''Syntax error : ''{'' However when I take it out of the class and just put it into a regular cpp it compiles fine. Why won''t this work in my class? Thanks Quiggy What am I doing wrong?

##### Share on other sites
porthios    130
You have to initialize variables within your constructor, not on the same line as you delcare them within your class.

##### Share on other sites
yes but how can you initialize an array after its been declared? i dont know the answer to this question either, but id like to know. ive had the same problem in the past and posted it here, and the answer wasnt what i wanted something about pointers to pointers and such. i dunno, man. just make it a global like i did

##### Share on other sites
Palidine    1315
you can''t initialize member variables in your class definition. C++ is different from java that way. the short is that you can''t do what you want to do. you have to do something like this:

class CGameData{public:    CGameData();private:    char GameBoard[5];};CGameData::CGameData(){    GameBoard[0] = '' '';    GameBoard[1] = ''|'';    GameBoard[2] = '' '';    GameBoard[3] = ''|'';    GameBoard[4] = '' '';}

pain in the butt, but there you go. if you want to be 1337 about it, write a txt file parser and read your gameboard in from a .txt file. that way you don''t have to recompile your game to change the game board.

-me

##### Share on other sites
Quiggy    122
Wow that was fast!

I put it into the constructor and it works like a charm.

Thanks for the help.

Quiggy.