lundi 28 mars 2016

Preferred way of class member initialization?

class A { public: int x[100]; };

Declaring A a will not initialize the object (to be seen by garbage values in the field x). The following will trigger initialization: A a{} or auto a = A() or auto a = A{}.

Should any particular one of the three be preferred?

Next, let us make it a member of another class:

class B { public: A a; };

The default constructor of B appears to take care of initialization of a. However, if using a custom constructor, I have to take care of it. The following two options work:

class B { public: A a;  B() : a() { } };

or:

class B { public: A a{};  B() { } };

Should any particular one of the two be preferred?

Aucun commentaire:

Enregistrer un commentaire