I write games in C++ with SDL. I wrote games in C for more than a year and now I've been writing in C++ for the last 7 months. I'm trying to avoid almost all global variables and move to a system of ownership, where every object is owned by something else. This way I can just manage the life of classes who have shared_ptr members and almost never worry about freeing pointers.
For example, my game is a class with its subsystems.
class Game
{
public:
Game();
~Game();
void runFrame();
std::shared_ptr<Display> display;
std::shared_ptr<Audio> audio;
std::shared_ptr<Save> save;
};
But I run into messy looking nested classes, like my audio class below.
class Audio
{
public:
Audio(Game& parent);
~Audio();
struct MusicFiles;
struct SfxFiles;
std::shared_ptr<MusicFiles> musicFiles;
std::shared_ptr<SfxFiles> sfxFiles;
private:
class Music
{
public:
class File
{
public:
File(Music& parent, std::string fileAddr);
~File();
void play();
void fadeIn();
void stop();
private:
Music& _parent;
std::string addr;
Mix_Music* chunk;
};
Music(Audio& parent);
~Music();
void setVolume();
private:
Audio& _parent;
bool _enabled;
int _volume;
};
class Sfx
{
public:
class File
{
public:
File(Sfx& parent, std::string fileAddr);
~File();
void play();
void stop();
private:
Sfx& _parent;
std::string addr;
Mix_Chunk* chunk;
int channel;
};
Sfx(Audio& parent);
~Sfx();
void setVolume();
private:
Audio& _parent;
bool _enabled;
int _volume;
};
Game& _parent;
Music _music;
Sfx _sfx;
};
I have nested classes because I dislike having to write "Music" or "Sfx" in every function name, like setMusicVolume(), setSfxVolume(), setMusicHook(), setSfxHook(), etc. etc. I can pull the nested classes out but Music and Sfx only need to exist within the Audio class. I'd rather reorganize everything and have a better design.
Do you have any better design suggestions?