jeudi 19 mars 2015

Declaring object onto the stack in class definition vs in constructor


When I declare the "Level" object in the "LevelEditor" class definition like so, everything works fine:



class LevelEditor
{
public:
LevelEditor(int w, int h, Shader* shader)
{
width = w;
height = h;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
tile[x][y] = new WorldSprite(tileWidth * x, tileHeight * y, tileWidth, tileHeight, shader);
}
}
}

//...
private:

//...
Level level = Level(50, 50);

WorldSprite* tile[300][300];

//tile characteristics
int tileWidth = 50;
int tileHeight = 50;

//flags
bool editing = true;
};


But when I declare the "Level" object in the "LevelEditor" constructor like so, I get a stack overflow:



class LevelEditor
{
public:
LevelEditor(int w, int h, Shader* shader)
{
width = w;
height = h;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
tile[x][y] = new WorldSprite(tileWidth * x, tileHeight * y, tileWidth, tileHeight, shader);
}
}
//NOTE: width and height both equal 50
level = Level(width, height);
}

//...
private:

//...
Level level;

WorldSprite* tile[300][300];

//tile characteristics
int tileWidth = 50;
int tileHeight = 50;

//flags
bool editing = true;
};


This makes me wonder what the difference is between declaring a variable in the class definition and in the constructor is besides the fact of the time of defining the variable. Any idea of what the cause could be? and how I could declare the "Level" object in the constructor without having to put anything on the heap?




Aucun commentaire:

Enregistrer un commentaire