Member Initialization List over Assignment

To start with, this article is not actually my own words. It is a small section of the fantastic book "Efective C++: 55 Specific Ways tom Improve Your Programs and Designs", by Scott Meyers, and I thought it warranted an article being made for it as it gives some very useful information.

Try not to get held up on the first few sentences as this is mid flow in the chapter...


For almost everything else, the responsibility for initialization falls on constructors. The rule there is simple: make sure that all constructors initialize everything in the object.

The rule is easy to follow, but it’s important not to confuse assignment with initialization. Consider a constructor for a class representing entries in an address book:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Class PhoneNumber { … };

Class ABEntry {                                              // ABEntr = “Address Book Entry”
public:
    ABEntry(const std::String& name, const std::string& address,
                    const std::list<PhoneNumber>& phones);
private:
    std::string theName;
    std::string theAddress;
    std::list<PhoneNumber> thePhones;
    int numTimesConsulted;
};
   
ABEntry(const std::String& name, const std::string& address,
                const std::list<PhoneNumber>& phones)
{
    theName = name;                                        // these are all assignments,
    theAddress = address;                                 // no initializations
    thePhones = phones;
    numTimesConsulted = 0;
}


This will yield ABEntry objects with the values you expect, but it’s still not the best approach. The rules of C++ stipulate that data members of an object are initialized before the body of a constructor is entered. Inside the ABEntry constructor, theName, theAddress, and thePhones aren’t being initialized, they’re being assigned. Initialization took place earlier – when their default contructors were automatically called prior to entering the body of the ABEntry constructor. This isn’t true for numTimesConsulted, because it’s a built-in type. For it, there’s no guarantee it was initialized at all prior to its assignment.

A better way to write the ABEntry constructor is to use the member initialization list instead of assignments:

1
2
3
4
5
6
7
const std::String& name, const std::string& address,
                    const std::list<PhoneNumber>& phones)
: theName(name),
  theAddress(address),                                     // these are now all initializations
  thePhones(phones),
  numTimesConsulted(0)
{}                                                                     // the ctor body is now empty 


This constructor yields the same end result as the one above, but it will often be more efficient. The assignment-based version first called default constructors to initialize theName, theAddress, and thePhones, then promptly assigned new values on top of the default-constructed ones. All the work performed in those default constructions was therefore wasted. The member initialization list approach avoids that problem, because the arguments in the initilization list approach avoids that problem, because the arguments in the initialization list are used as constructor arguments for the various data members. In this case, theName is copy-constructed from name, theAddress is copy-constructed from address, and thePhones is copy-constructed from phones. For most types, a single call to a copy constructor is more efficient – sometimes much more efficient – than a call to the default constructor followed by a call to the copy assignemnet operator.

For objects of built-in type like numTimesConsulted, there is no difference in cost between initialization and assignment, but for consistence, it’s often best to initialize everything via member initialization. Similarly, you cn use the member initilzation list even when you want to default-construct a data member; just specify nothing as an initialization argument.
Oh it's this thing!
Yes, people really do need to know this. The body of the constructor performs assignments; only the initializer list can actually "initialize" the variable.
closed account (S6k9GNh0)
The constructor body can perform initialization, it's just not recommended since it makes for restrictions. An easy rule of thumb is ALWAYS use initialization lists.
Last edited on
Be weary of "always" rules.

I generally agree that you should try to prefer initialization lists, so I don't mean to disagree with you. In fact I strongly agree that initialization lists are a better solution most of the time. I'm just trying to point out some "gotchas":


There are caveats to the initializer list:

-) The items are not necessarily initialized in the order that they're listed in the initializer list. They're actually initialized in the order in which they're declared in the class. GCC (and maybe modern VS) will throw a warning/error if the orders mismatch, but it still something to be weary about. For example:

1
2
3
4
5
6
7
8
9
10
11
12
class Foo
{
  vector<int> vec;
  int count;

public:
  Foo(int val)
  : count(val * 3),
    vec(count)
  {
  }
};


This above code is no good because 'count' is used to initialize 'vec' before count has been initialized (vec is initialized first because it was declared first).

Of course you could change the order in which your variables are declared. But then what happens if you change them again later? Or what if your initialization is more complex?


-) They can complicate multiple ctors and produce a lot of redundant code. Say you have a class that has 20 members and 5 different ctors (most of which are initialized the same way for every ctor).

Is it wise to repeat the initialzation for every ctor? I'd say no. Duplicate code is bad for many reasons... the biggest one is that it makes updating the code more difficult. What if you need to change initialization (like if you add a new member, or need to change the initialzation state slightly)? It's very easy to forget to change one of the many ctors, and if you do you have a gnarly bug that could rip you a new one and be hard to expose. Such a situation would be better met with a minimal initialzation list, and a call to a common "Init" function that does most of the initialization.

But I think this problem is solved by C++0x since it allows ctors to call other ctors, so this may be a moot point soon.
Last edited on

-) They can complicate multiple ctors and produce a lot of redundant code. Say you have a class that has 20 members and 5 different ctors (most of which are initialized the same way for every ctor).


That's the only somewhat legitimate reason, though that can somewhat be mitigated
by use of a helper base class (it seems like I just read something about this somewhere,
but at this late hour I can't remember what or where)

The first reason given should not be a problem as I would think all modern compilers
(even MSoft) would warn about initialization order.

Anyway, yes, C++0x has solved this problem.
They can complicate multiple ctors and produce a lot of redundant code. Say you have a class that has 20 members and 5 different ctors (most of which are initialized the same way for every ctor).


This can also be mitigated with modeling tools where you specify initial values for attributes and the tool autogenerates your constructors and their initialization lists. When working on large scale projects I have always used some kind of modeling tool. I think that it is really important to try to use the modeling tools to your advantage rather than to make the common function for initialization. I also think that it is pretty rare that you need many constructors for a class. To avoid this you can sometimes use default values for parameters so that some can be optionally specified by the caller instead of having many forms of the same constructor. Your default constructor could be a constructor where all of the args have default values. You generally run into the issue that disch is talking about when you are writing classes manually without the assistance of a complex IDE.
The constructor body can perform initialization, it's just not recommended since it makes for restrictions. An easy rule of thumb is ALWAYS use initialization lists.


Sorry but I have to correct this statement as it is very dangerous. As a matter of fact we just saw a thread in the beginner forum today where this mistake was made. The poster had created a variable in the body of the constructor with the same name as the class attribute thinking that they were initializing the class attribute. The only thing that you can initialize in the body of a constructor are things that are local to the body and they will be destroyed when the constructor finishes. As silly as this example seems to a pro, I have seen beginners make this mistake many times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Foo
{
   public: 
   Foo() 
   { 
         // this is totally different than Foo::array and will be initialized but destroyed
         // when the constructor finishes.  Foo::array was never initialized. local array
         // is created in stack memory and destroyed when the constructor finishes.
          int array[25] { 0 };
   }

   private:
      int array[25];
};
There is a difference in C++ between initialization and assignment. [/i]Initialization[/i]
occurs when an object is constructed. Assignment occurs after an object is already initialized.

Therefore, no, you cannot initialize a member in the body of the constructor; you can only assign
it.
Topic archived. No new replies allowed.