Question

I'm new to C++ and I have a question...

I tried answering the question myself by making a test application... in debug, the class B initialization generates less assembly code, but in release mode, I can't really say... it optimizes the initializations away :(

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;
};

Is there any advantage of using

B b = {1, 2, 3, 4}

instead of

A a = A(1, 2, 3, 4);

?

Was it helpful?

Solution

I don't know about performance advantages, but in general using the constructor is preferred.

This is because with A, members a,b,c,d can be made private. Thus, you get encapsulation with your A approach, which you don't have in B.

As a class designer, you can enforce strict usage and assignment of member variables via a constructor. In your B, class scenario, you can't.

So while you may get a small boost in perf, for using B, I would wager it to be negligible, and would be negated by the potential headache of having unprotected class members.

OTHER TIPS

For a global objects and static class members, the initializer list doesn't invoke any code on run time. (Initialization data is stored directly in the binary).

If you are initializing a lot of objects, or if the constructor code is expensive / large, this can make a notable difference at load time.

As said, this is true only for plain old data, i.e. everything that can be initialized with an initializer list in C++ < 0x

You don't have to explicitly write the constructor and C code using this type of initialization works in C++.

If you have complicated compound structures of simple data fileds, initialization of variables can be easier with initialization lists than with constructors:

B barr[5] = {
    {1,2,3,4},
    {5,6,7,8},
    ...
  };

The disadvantage that it (currently) only works for simple classes with only POD member variables and that programmers might not be very familiar with the syntax.

Most classes can't use initialization lists (yet!), so you are better off using a constructor just to be consistent. In c++0x std::initializer_list will exist to allow this syntax for any class.

Below are the scenarios when initializer list is used:

  1. For initialization of non-static const data members.
  2. For initialization of reference members.
  3. For initialization of member objects which do not have default constructor.
  4. For initialization of base class members.
  5. When constructor’s parameter name is same as data member.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top