+ 2
Benefit of class member initialization in declaration
Hello AFIK, class data member cannot be initialized in class declaration. Seems it is allowed in new versions of C++. Is it really useful to have this feature? Class constructor was already there for this purpose, then what is the need of same? Refer below code and initialization of a and b could have done in constructor, then what made C++ to allow declaration in class itself.... Does this memory allocated when required number of objects created in main function? https://code.sololearn.com/ca2a1732A23a
3 Respostas
+ 4
This is a good question. The only reason I can come up with is in cases where specific values must be assigned initially and you don’t want the potential risk of incorrect values getting passed via the constructor.
+ 2
Correct. Memory is not allocated until an object is created. As you can create multiple objects for a given class, you could consume much more memory than the variables stand alone.
0
Yeah sounds good....but It could have been achieved by default argument in constructor...
Also what make me think more is memory of int and int* when class is defined... Does this not occupied till we create object even though values are assigned in declaration?