OpenGL Maniac OpenGL Maniac - 1 month ago 10
C++ Question

C / C++ Can't change pointer value, stays nullptr

I have a nullptr in Game.h

Tile * _playerTile = nullptr;


I give it to the Player constructor in Game.cpp

Game::Game(int winW, int winH, string winTitle) :
_inputManager(),
_textureLoader(),
_tilemapLoader(),
_player(_playerTile) // <----
{}


Player.h:

Tile * _tile = nullptr;


The player class assigns the pointer to
_tile
in Player.cpp

Player::Player(Tile * tile) :
_tile(tile)
{

}


When I change
_playerTile
in Game.cpp constructor,
_tile
stays nullptr.

_playerTile = _tilemapLoader.getPlayerTile(); //getPlayerTile returns a pointer to a dynamic instance created with "new"


Does anyone know why the pointer doesn't change?

Answer

You are running

_playerTile = _tilemapLoader.getPlayerTile(); //getPlayerTile returns a pointer to a dynamic instance created with "new"

Inside the constructor of Game. The part in the constructor between braces { } gets executed after the member initialization list:

_inputManager(),
_textureLoader(),
_tilemapLoader(),
_player(_playerTile)

So your Player constructor is invoked with a nullptr tile. Just because later on you change _playerTile doesn't mean you change the other pointer in Player. That's not how pointers work. This part:

_tile(tile)

Copies the memory address of the pointer to point to that memory address. But since it's still nullptr it'll stay nullptr unless you change it directly.

Comments