Search code examples
c++visual-studiopointersnullpass-by-reference

Pointer is NULL even when directly assigned to non-NULL pointer


Okay so sorry if the title is hard to understand I wasn't sure what to call this.

I have a pointer in my gameObject object that points to a object called game and is by default a nullptr.

class GameObject
{
public:
    class Game* game = nullptr;
    GameObject(float x, float y, const std::string &path);
};

In game I then call addGameObject which add the gameObject to the vector and sets the gameObjects game pointer to itself (this).

void Game::addGameObject(GameObject &gameObject) {
    m_objectList->push_back(gameObject);
    gameObject.game = this;
}

But in the gameObject when I try to access the game pointer after it is added to the game, the pointer to game is always null.

void GameObject::update() {
    if(game)
        std::cout << game->deltaT(); // will never be called
}

The update function in gameObject is called from the game as shown:

void Game::update()
{
    for (auto gameObject = m_objectList->begin(); gameObject != m_objectList->end(); gameObject++) {
        // update
        gameObject->update();
    }
}

This is how the project is setup. A game is made and so is a gameObject called kappa, kappa is then added to the game.

int main() {
    Game game(720, 480);
    GameObject kappa(game.getWidth() / 2, game.getHeight() / 2, "../graphics/Kappa.jpg");
    game.addGameObject(kappa);
    

    while (game.isRunnig()) {
        game.update(); // calls all gameObjects added update function
    }
}

I thought there was something wrong with the 'this' keyword but when using the debugger it showed that it was not a nullptr and was working as intended. So my best guess is that the game pointer is being derefrenced somewhere along the way. Possibly something wrong with my understanding of pass by refrence.

P.S. The gameObject does get stored in the vector in game as intended.


Solution

  • When adding the GameObject to the m_objectList, the value of that GameObject is being copied so any changes made after that addition is worthless as the Game object is only awear of the copy.

    Using a vector of pointers solves this issue.

    void Game::addGameObject(GameObject& gameObject) {
        GameObject* go = &gameObject;
        go->game = this;
        m_objectList->push_back(go);
    }