BeeBand
BeeBand

Reputation: 11493

How sensible is it to pass functions to initialisation lists in a constructor?

Let's say I have a class Engine that looks a bit like this:

class Engine
{
  public:
  private:
     Game * m_pGame;
}

And then I want to use an initialisation list for it's constructor:

// Forward declaration of the function that will return the
// game instance for this particular game. 
extern Game * getGame();

// Engine constructor
Engine::Engine():
  m_pGame(getGame())
{

}

Is that initialiser for m_pGame sensible?

What I mean is - is it OK/good practice to use a function to initialise a member variable in a constructor?

Upvotes: 1

Views: 98

Answers (1)

Kylotan
Kylotan

Reputation: 18449

Initialiser lists don't care how the values get there. What you have to worry about is making sure that a reasonable value is provided. If getGame() is sure to return a valid pointer, then there's no reason why this would be a problem.

Perhaps a better question is, why don't you call getGame first and pass that in as an argument? eg:

Engine::Engine(Game* game):
  m_pGame(game)
{
}

// later...
Engine* the_engine = new Engine(getGame());

That gives you more flexibility over how you configure an Engine in future, and doesn't hard-code the dependency on the getGame function.

Upvotes: 8

Related Questions