Pointers and inheritance - Am I doing this right?

I have a base class called Game
I am extending it as GameOne, GameTwo, etc
I want to keep a reference to the current game that is active.

in ofApp.h

Game* currentGame = NULL;

in ofApp.cpp

ofApp::newGame(int index){
    if(index == 1) {
       currentGame = new Game1();
    }
    if(index == 2) {
       currentGame = new Game2();
    }
}

ofApp::clearGame(){
     if (currentGame) {
        delete currentGame;
    }
}

ofApp::draw(){

    if(currentGame) {
        currentGame->draw();
    }
}

GameOne.h

...
class GameOne : public Game{
    ...
}

Delete does not seem to be clearing the reference. Am I going about this the right way? I want to keep a reference to the current game, but I also need a state when no game is loaded.

in ofApp.h put:

Game* currentGame;

in ofApp.cpp:

ofApp::clearGame(){
 if (currentGame) {
    delete currentGame;
    currentGame = NULL;
}
}
1 Like

And I would do this for minimizing potential memory leakage:

ofApp::newGame(int index){
	if(index == 1) {
		if (currentGame) delete currentGame;
		currentGame = new Game1();
	}
	if(index == 2) {
		if (currentGame) delete currentGame;
		currentGame = new Game2();
	}
}
1 Like

When I was still learning c++, I found this a great resource http://www.learncpp.com/

He goes into a good bit of detail on deleting objects. Rule of thumb. After you delete it, set it to NULL always. He goes into why that’s important in his tutorial.

2 Likes

Great stuff. Thanks for the help all!