When I first started working with object-oriented programming languages, I was taught the following rule:
When declaring a field in a class, don't initialize it yet. Do that in the constructor.
An example in C#:
public class Test
{
private List<String> l;
public Test()
{
l = new List<String>();
}
}
But when someone recently asked me why to do that, I couldn't come up with a reason. I'm not really familiar with the internal workings of C# (or other programming languages, for that matter, as I believe this can be done in all OO languages).
So why is this done? Is it security? Properties?
Assigning const or reference member variables values in the body of the constructor is not sufficient. C++ provides another way of initializing member variables that allows to initialize member variables when they are created rather than afterwards. This is done through use of an initialization list.
You should don’t define a default constructor that only initializes data members; use in-class member initializers instead which works as a good fallback in case you forget to initialize something. Example — A bad class that misses one initialization in a constructor
If non-static const data members in your class have default constructors & you don't use constructor initializer list, you won't be able to initialize them to intended state as they will be initialized to their default state.
As explained in the C++ Core Guidelines C.49: Prefer initialization to assignment in constructors it prevents unnecessary calls to default constructors.
If you have multiple constructors, you might want to initialize a field to different values
When you initialize the field in the constructor, there can be no confusion over when exactly it is initialized in regard to the rest of the constructor. This may seem trivial with a single class, but not so much when you have an inheritance hierarchy with constructor code running at each level and accessing superclass fields.
The C# compiler will take any non-static member intialization that you do inline and move it into the constructor for you. In other words this:
class Test
{
Object o = new Object();
}
gets compiled to this:
class Test
{
Object o;
public Test()
{
this.o = new Object();
}
}
I am not sure how compilers for other languages handle this but as far as C# is concerned it is a matter of style and you are free to do whichever you wish. Please note that static fields are handled differently: read this article for more information on that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With