Benefit of copying pointer class arguments to class members?

76 views Asked by At

I have a player class that uses my DirectX Graphics class to create surfaces and draw sprites.

I am passing the graphics class as a pointer to the player class methodlike this:

**game.cpp**
m_pPlayer->Init(Graphics* graphics);

Inside the player class my Init method passes the pointer to another pointer method. Is there any benefit to creating another graphics pointer in the player class and copying the pointer argument instead?

So this:

**player.cpp**
m_pSurface->Init(graphics, m_width, m_height);

vs this:

**player.cpp**
m_pGraphics = graphics;
m_pSurface->Init(m_pGraphics, m_width, m_height);

I know that having a m_pGraphics pointer allows me to reuse the pointer again in the same class, such as my drawing method but I call the method in the player class anyway so can't I just keep passing the pointer over and over again?

1

There are 1 answers

3
Chris Drew On

This is just a matter of style and is unlikely to have any effect on performance. Copying pointers is very cheap and I would leave it to the compiler to optimize.

If player uses the Graphics object a great deal it would be reasonable to store a pointer in a member variable instead of passing it in all the time. It may make the member function signatures on player shorter which is good.

You do need to be sure that the member pointer to the Graphics object remains valid whenever it is used. Is it still the correct Graphics object and is it still alive? If you pass the pointer every time you might not have this complication.