Problem creating levels using inherited classes/polymorphism
Posted
by
Adam
on Game Development
See other posts from Game Development
or by Adam
Published on 2012-01-15T23:23:25Z
Indexed on
2012/09/29
15:53 UTC
Read the original article
Hit count: 246
I'm trying to write my level classes by having a base class that each level class inherits from...The base class uses pure virtual functions.
My base class is only going to be used as a vector that'll have the inherited level classes pushed onto it...This is what my code looks like at the moment, I've tried various things and get the same result (segmentation fault).
//level.h
class Level
{
protected:
Mix_Music *music;
SDL_Surface *background;
SDL_Surface *background2;
vector<Enemy> enemy;
bool loaded;
int time;
public:
Level();
virtual ~Level();
int bgX, bgY;
int bg2X, bg2Y;
int width, height;
virtual void load();
virtual void unload();
virtual void update();
virtual void draw();
};
//level.cpp
Level::Level()
{
bgX = 0;
bgY = 0;
bg2X = 0;
bg2Y = 0;
width = 2048;
height = 480;
loaded = false;
time = 0;
}
Level::~Level()
{
}
//virtual functions are empty...
I'm not sure exactly what I'm supposed to include in the inherited class structure, but this is what I have at the moment...
//level1.h
class Level1: public Level
{
public:
Level1();
~Level1();
void load();
void unload();
void update();
void draw();
};
//level1.cpp
Level1::Level1()
{
}
Level1::~Level1()
{
enemy.clear();
Mix_FreeMusic(music);
SDL_FreeSurface(background);
SDL_FreeSurface(background2);
music = NULL;
background = NULL;
background2 = NULL;
Mix_CloseAudio();
}
void Level1::load()
{
music = Mix_LoadMUS("music/song1.xm");
background = loadImage("image/background.png");
background2 = loadImage("image/background2.png");
Mix_OpenAudio(48000, MIX_DEFAULT_FORMAT, 2, 4096);
Mix_PlayMusic(music, -1);
}
void Level1::unload()
{
}
//functions have level-specific code in them...
Right now for testing purposes, I just have the main loop call Level1 level1; and use the functions, but when I run the game I get a segmentation fault. This is the first time I've tried writing inherited classes, so I know I'm doing something wrong, but I can't seem to figure out what exactly.
© Game Development or respective owner