+ 1
IN CPP Using class initializer list?
In CPP should we be using class initializer list when assinging class properties to a value or a constructor ...and is there any drawback of not using it?
2 Antworten
+ 7
Always use initializer !
(An example at the end.)
1: readable and tidy code.
Put all data members inside initializer,
even the members you think aren't needed for
your constructor. default data.
You'll always know where to find information
of the composition,state,defaults of your class.
2: efficiency.
member objects constructors are initialized
before the body of your constructor, no reason
to assign a value later..
3: Make sure an instance of your class it's initialized.
If a member is not initialized it can lead to
undefined behaviour!
For built in types(int for example) it's hard to
know if they are initialized themselves.
For objects... well if they are designed whit
these rules it's fine.
1+3: if you put all your data members on initializer
you'll clearly know which data is initialized and
which not.
4: const and references MUST be initialized.
class myClass
{
public:
myClass(string _name): // you pass only this
level (1), // if these wasn't initialized they
HP (87.9), // can have strange value, maybe not
// wanna risk?
// it's always good to manually
// initialize built-in types
name ( _name) // and here..
// name is a string object.. it has a constructor
// so it is created and initialized before the body
// of our class constructor.. this way you pass
// directly _name parameter to his constructor.
// why assign _name later inside the body??
{
// body of constructor
}
....
..//a lot of code...
//and finally data members
private:
int level; // this way members are declared
float HP; // here , and defined in initializer
string name;
};
+ 5
IIRC constructor intializer can be used to initialize a const member while that's not the case with constructor code.
https://www.sololearn.com/learn/CPlusPlus/1896/
Cmiiw