views:

172

answers:

2

Class A uses an initializer list to set the member to the paramter value, while Class B uses assignment within the constructor's body.

Can anyone give any reason to prefer one over the other as long as I'm consistent?

class A
{
    String _filename;

    A(String filename) : _filename(filename)
    {
    }
}


class B
{
    String _filename;

    B(String filename)
    {
        _filename = filename;
    }
}
+12  A: 

The first one is not legal in C#. The only two items that can appear after the colon in a constructor are base and this.

So I'd go with the second one.

JaredPar
A: 

Did you mean C++ instead of C#?

For C++, initializer lists are better than assignment for a couple of reasons:

  • For POD types (int, float, etc..), the optimizer can often do a more efficient memcpy behind the scenes when you provide initializers for the data.
  • For non-POD types (objects), you gain efficiency by only doing one construction. With assignment in the constructor, the compiler must first construct your object, then assign it in a separate step (this applies to POD types as well).
Jeremy Bell