Advantage of using aggregate initialization list over constructor?
I am new to C ++ and I have a question ...
I tried to answer the question myself by making a test application ... in debug, class B initialization generates less assembly code, but in release mode I can't tell ... it optimizes initialization :(
Let's say I have two classes:
class A
{
public:
int a, b, c, d;
A(int _a, int _b, int _c, int _d) : a(_a), b(_b), c(_c), d(_d)
{
}
};
class B
{
public:
int a, b, c, d;
};
Are there any advantages to using
B b = {1, 2, 3, 4}
instead
A a = A(1, 2, 3, 4);
?
a source to share
I am not aware of the performance benefits, but in general, using the constructor is preferred.
This is because with A, the members a, b, c, d can be made private. This way you get encapsulation with your approach A, which you don't have in B.
As a constructor for a class, you can enforce strict use and assignment of member variables through the constructor. In your class B scenario, you cannot.
So, while you might get a little performance boost to use B, I would put it at a disadvantage and be negative about the potential headache when you had unprotected class members.
a source to share
For globals and static class members, the initializer list does not call any code at runtime. (Initialization data is stored directly in binary format).
If you are initializing a lot of objects, or if the constructor code is expensive / large, this can have a noticeable impact on load times.
As said, this is only true for plain old data, i.e. anything that can be initialized with an initializer list in C ++ <0x
a source to share
You don't need to explicitly write constructor and C code using this type of initialization in C ++.
If you have a complex composite structure of simple data fields, initializing variables may be easier with initialization lists than with constructors:
B barr[5] = {
{1,2,3,4},
{5,6,7,8},
...
};
The downside is that it (currently) only works for simple classes with only POD member variables and that programmers may not be very good at syntax.
a source to share
Following are the scenarios when an initializer list is used:
- For initializing non-static data members, const.
- To initialize referenced elements.
- To initialize member objects that do not have a default constructor.
- To initialize base classes.
- When the name of the constructor parameter is the same as the name of the data item.
a source to share