1

What is better - initialize simple type members in class declaration or in constructor initialization list?

class A {

    // ...

private:
    int m_member = 1;

    // ...

}

or

A::A() : m_member(1) {

    // ...

}

?

vladon
  • 8,158
  • 2
  • 47
  • 91
  • Eventually is the same thing. IMHO in class initialization is better because you have the variable and its default value in the same place. – 101010 Jul 03 '15 at 09:37
  • 1
    As the former is not standard until C++11, if you need portability to older language standards, the latter will get it for you. If "better" means compiles for both C++11, *and prior*, the latter is so. – WhozCraig Jul 03 '15 at 09:44
  • 1
    I have retracted my close vote as _primarily opinion based_. There were certainly reasons the in class initialization was introduced with the current standard. At least I tried to point out some aspects in my answer. – πάντα ῥεῖ Jul 03 '15 at 09:52
  • [C++11 member initializer list vs in-class initializer?](http://stackoverflow.com/q/27352021/3953764) – Piotr Skotnicki Jul 03 '15 at 21:06

1 Answers1

3

I think in class initialization was introduced in the current standard to enhance readability and consistency.

Without you'll need to take care about consistent initializations in every constructor.

Such it's better to use the 1st form you proposed:

class A {
   // ...
private:
    int m_member = 1;
    // ...
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190