Just a small question here but with a lot of code since it kind of deals with some of the finer details of objects within objects etc...
I'm making Pacman. I have a class to represent my map and a Sprite class which is used to handle every individual picture of every object in the game.
Here's my Map class in map.h:
#ifndef MAP_H
#define MAP_H
#include "sprite.h"
class Map
{
private:
static const int MAPTILES_X = 29;
static const int MAPTILES_Y = 32;
Sprite spr;
static enum Tiles
{
PASSABLE,
IMPASSABLE,
};
Tiles MapTiles [MAPTILES_X][MAPTILES_Y];
public:
Map();
~Map();
};
extern Map gameMap;
#endif
Here's map.cpp:
#include "map.h"
Map gameMap;
Map::Map()
{
spr.init("pacmap.png");
}
Map::~Map()
{
spr.free();
}
The init function is just a member of the Sprite class used to load in the appropriate image for a Sprite. I don't think there's any point showing it here, it's basically just the typical SDL image loading function where we convert the image to SDL display format etc.
The problem is that I get an exception with this code when using spr.init();
It occurs with SDL_Surface* temp found inside the init() function.
Basically, it seems pretty obvious that the Sprite object inside the Map object isn't being initialized properly and the init() function is looking for something that doesn't exist or isn't set up like it should be since temp is all full of "Cannot be Evaluated" in the debug output.
I figure I could just call gameMap.spr.init("pacmap.png"); as soon as it's required by the game,i.e. right before gameplay begins but that seems rather sloppy and besides, it's better that I learn what's going wrong here anyway.
Should I perhaps use a Sprite* instead of a Sprite inside the Map class? When using pointers the problem seems to disappear; I have a pointer that creates a new Menu gamestate which uses the same idea as my Map class but that works perfectly. Also, simply changing
extern Map gameMap
Map gameMap
to
extern Map* gameMap
Map* gameMap
appears to fix the problem.
Where's the problem here? Should I always use pointers in situations like this or is there a simpler way of fixing it that I've overlooked? I haven't really been coding for a few weeks so I'm probably a bit rusty by now anyway. Thanks for bearing with me if you've read this far :D