Assignement vs constructor initialisation

  • Thread starter Thread starter garethrichardadams
  • Start date Start date
G

garethrichardadams

Hello all,

If you've got a class, say StateManager. That class has got a stack. Is
there any difference between initialising the stack when the variable
is created and initialising the stack in the constructor???:

public class StateManager
{
Stack<GameState> m_stack = new Stack<GameState>();
}

OR

public class StateManager
{
Stack<GameState> m_stack;

public StateManager()
{
m_stack = new Stack<GameState>();
}
}


Thanks

Gareth
 
Hello all,

If you've got a class, say StateManager. That class has got a stack. Is
there any difference between initialising the stack when the variable
is created and initialising the stack in the constructor???:

public class StateManager
{
Stack<GameState> m_stack = new Stack<GameState>();
}

OR

public class StateManager
{
Stack<GameState> m_stack;

public StateManager()
{
m_stack = new Stack<GameState>();
}
}

The only difference is that you can handle exceptions in the ctor (although
this will rarely be useful for instance variables it is a good idea for
statics as otherwise they can't be caught by normal code)
 
Nick Hounsome wrote:

The only difference is that you can handle exceptions in the ctor (although
this will rarely be useful for instance variables it is a good idea for
statics as otherwise they can't be caught by normal code)

There's another difference - time of execution with respect to base
constructors.

If the base constructor calls a virtual method which is overridden in
the derived class, then variables initialised in the constructor
*won't* have been set yet (i.e. they'll have their default values), but
variables with initialisers alongside their declarations *will* have
been set.

This kind of subtlety is one of the many reasons why constructors
generally *shouldn't* call virtual methods.

Jon
 
Back
Top