C++ Initialization List Vs Assignments


What’s the deal with constructors?

Constructors build objects from dust.

Constructors are like “init functions”. They turn a pile of arbitrary bits into a living object. Minimally they initialize internally used fields. They may also allocate resources (memory, files, semaphores, sockets, etc).

“ctor” is a typical abbreviation for constructor.

Is there any difference between and ?

A big difference!

Suppose that is the name of some class. Then function declares a local object called :

But function declares a function called that returns a :

Can one constructor of a class call another constructor of the same class to initialize the object?

The answer below applies to Classic (pre-11) C++. This question covers the C++11 feature of constructors that call same-type constructors.


Let’s work an example. Suppose you want your constructor to call another constructor of the same class, say , in order that would help initialize the object. Unfortunately there’s no way to do this in Classic C++.

Some people do it anyway. Unfortunately it doesn’t do what they want. For example, the line does not call on the object. Instead it calls to initialize a temporary, local object (not), then it immediately destructs that temporary when control flows over the .

You can sometimes combine two constructors via a default parameter:

If that doesn’t work, e.g., if there isn’t an appropriate default parameter that combines the two constructors, sometimes you can share their common code in a private member function:

BTW do NOT try to achieve this via placement new. Some people think they can say within the body of . However that is bad, bad, bad. Please don’t write me and tell me that it seems to work on your particular version of your particular compiler; it’s bad. Constructors do a bunch of little magical things behind the scenes, but that bad technique steps on those partially constructed bits. Just say no.

Is the default constructor for always ?


A “default constructor” is a constructor that can be called with no arguments. One example of this is a constructor that takes no parameters:

Another example of a “default constructor” is one that can take arguments, provided they are given default values:

Which constructor gets called when I create an array of objects?

’s default constructor (except as discussed below).

If your class doesn’t have a default constructor, you’ll get a compile-time error when you attempt to create an array using the above simple syntax:

However, even if your class already has a default constructor, you should try to use rather than an array (arrays are evil). lets you decide to use any constructor, not just the default constructor:

Even though you ought to use a rather than an array, there are times when an array might be the right thing to do, and for those, you might need the “explicit initialization of arrays” syntax. Here’s how:

Of course you don’t have to do for every entry — you can put in any numbers you want, even parameters or other variables.

Finally, you can use placement-new to manually initialize the elements of the array. Warning: it’s ugly: the raw array can’t be of type , so you’ll need a bunch of pointer-casts to do things like compute array index operations. Warning: it’s compiler- and hardware-dependent: you’ll need to make sure the storage is aligned with an alignment that is at least as strict as is required for objects of class . Warning: it’s tedious to make it exception-safe: you’ll need to manually destruct the elements, including in the case when an exception is thrown part-way through the loop that calls the constructors. But if you really want to do it anyway, read up on placement-new. (BTW placement-new is the magic that is used inside of . The complexity of getting everything right is yet another reason to use .)

By the way, did I ever mention that arrays are evil? Or did I mention that you ought to use a unless there is a compelling reason to use an array?

Should my constructors use “initialization lists” or “assignment”?

Initialization lists. In fact, constructors should initialize as a rule all member objects in the initialization list. One exception is discussed further down.

Watch this space for discussion of Non Static Data Member Initialization in C++11

Consider the following constructor that initializes member object using an initialization list: whatever. The most common benefit of doing this is improved performance. For example, if the expression whatever is the same type as member variable , the result of the whatever expression is constructed directly inside — the compiler does not make a separate copy of the object. Even if the types are not the same, the compiler is usually able to do a better job with initialization lists than with assignments.

The other (inefficient) way to build constructors is via assignment, such as: whatever. In this case the expression whatever causes a separate, temporary object to be created, and this temporary object is passed into the object’s assignment operator. Then that temporary object is destructed at the . That’s inefficient.

As if that wasn’t bad enough, there’s another source of inefficiency when using assignment in a constructor: the member object will get fully constructed by its default constructor, and this might, for example, allocate some default amount of memory or open some default file. All this work could be for naught if the whatever expression and/or assignment operator causes the object to close that file and/or release that memory (e.g., if the default constructor didn’t allocate a large enough pool of memory or if it opened the wrong file).

Conclusion: All other things being equal, your code will run faster if you use initialization lists rather than assignment.

Note: There is no performance difference if the type of is some built-in/intrinsic type, such as or or . But even in these cases, my personal preference is to set those data members in the initialization list rather than via assignment for consistency. Another symmetry argument in favor of using initialization lists even for built-in/intrinsic types: non-static and non-static reference data members can’t be assigned a value in the constructor, so for symmetry it makes sense to initialize everything in the initialization list.

Now for the exceptions. Every rule has exceptions (hmmm; does “every rule has exceptions” have exceptions? reminds me of Gödel’s Incompleteness Theorems), and there are a couple of exceptions to the “use initialization lists” rule. Bottom line is to use common sense: if it’s cheaper, better, faster, etc. to not use them, then by all means, don’t use them. This might happen when your class has two constructors that need to initialize the object’s data members in different orders. Or it might happen when two data members are self-referential. Or when a data-member needs a reference to the object, and you want to avoid a compiler warning about using the keyword prior to the that begins the constructor’s body (when your particular compiler happens to issue that particular warning). Or when you need to do an … test on a variable (parameter, global, etc.) prior to using that variable to initialize one of your members. This list is not exhaustive; please don’t write me asking me to add another “Or when…”. The point is simply this: use common sense.

How should initializers be ordered in a constructor’s initialization list?

Immediate base classes (left to right), then member objects (top to bottom).

In other words, the order of the initialization list should mimic the order in which initializations will take place. This guideline discourages a particularly subtle class of order dependency errors by giving an obvious, visual clue. For example, the following contains a hideous error.

The output of this program follows.

Note that is used () before it is initialized (). If instead the programmer had read and abided by the guideline in this FAQ, the error would be more obvious: the initialization list of would have read , visually indicating that was being used before being initialized.

Not all compilers issue diagnostic messages for these cases. You have been warned.

Is it moral for one member object to be initialized using another member object in the initializer expression?

Yes, but use care and do that only when it adds value.

In a constructor’s initialization list, it is easiest and safest to avoid using one member object from object in the initialization expression of a subsequent initializer for object. This guideline prevents subtle order-dependency errors if someone reorganizes the layout of member objects within the class.

Because of this guideline, the constructor that follows uses rather than , even though they are otherwise equivalent. The prefix avoids an unnecessary and avoidable order dependency.

An unnecessary order dependency on the class layout of and would have been introduced if the constructor’s initialization of had used rather than . However using within a constructor body () is okay. No order dependency is introduced since the entire initialization list is guaranteed to finish before the constructor body begins executing.

What if one member object has to be initialized using another member object?

Comment the declaration of the effected data members with .

If a constructor initializes a member object of object using another member object of object, rearranging the data members of the class could break the constructor. This important maintenance constraint should be documented in the class body.

For example, in the constructor below, the initializer for uses to avoid a redundant call to , which introduces an order dependency in the class body.

Note that the comment is listed with the effected data members in the class body, not with the constructor initialization list where the order dependency was actually created. That is because the order of member objects in the class body is critical; the order of initializers in the constructor initialization list is irrelevant.

Should you use the pointer in the constructor?

Some people feel you should not use the pointer in a constructor because the object is not fully formed yet. However you can use in the constructor (in the body and even in the initialization list) if you are careful.

Here is something that always works: the body of a constructor (or a function called from the constructor) can reliably access the data members declared in a base class and/or the data members declared in the constructor’s own class. This is because all those data members are guaranteed to have been fully constructed by the time the constructor’s body starts executing.

Here is something that never works: the body of a constructor (or a function called from the constructor) cannot get down to a derived class by calling a member function that is overridden in the derived class. If your goal was to get to the overridden function in the derived class, you won’t get what you want. Note that you won’t get to the override in the derived class independent of how you call the member function: explicitly using the pointer (e.g., ), implicitly using the pointer (e.g., ), or even calling some other function that calls the member function on your object. The bottom line is this: even if the caller is constructing an object of a derived class, during the constructor of the base class, your object is not yet of that derived class. You have been warned.

Here is something that sometimes works: if you pass any of the data members in object to another data member’s initializer, you must make sure that the other data member has already been initialized. The good news is that you can determine whether the other data member has (or has not) been initialized using some straightforward language rules that are independent of the particular compiler you’re using. The bad news is that you have to know those language rules (e.g., base class sub-objects are initialized first (look up the order if you have multiple and/or inheritance!), then data members defined in the class are initialized in the order in which they appear in the class declaration). If you don’t know these rules, then don’t pass any data member from the object (regardless of whether or not you explicitly use the keyword) to any other data member’s initializer! And if you do know the rules, please be careful.

What is the “Named Constructor Idiom”?

A technique that provides more intuitive and/or safer construction operations for users of your class.

The problem is that constructors always have the same name as the class. Therefore the only way to differentiate between the various constructors of a class is by the parameter list. But if there are lots of constructors, the differences between them become somewhat subtle and error prone.

With the Named Constructor Idiom, you declare all the class’s constructors in the or sections, and you provide methods that return an object. These methods are the so-called “Named Constructors.” In general there is one such method for each different way to construct an object.

For example, suppose we are building a class that represents a position on the X-Y plane. Turns out there are two common ways to specify a 2-space coordinate: rectangular coordinates (X+Y), polar coordinates (Radius+Angle). (Don’t worry if you can’t remember these; the point isn’t the particulars of coordinate systems; the point is that there are several ways to create a object.) Unfortunately the parameters for these two coordinate systems are the same: two s. This would create an ambiguity error in the overloaded constructors:

One way to solve this ambiguity is to use the Named Constructor Idiom:

Now the users of have a clear and unambiguous syntax for creating s in either coordinate system:

Make sure your constructors are in the section if you expect to have derived classes.

The Named Constructor Idiom can also be used to make sure your objects are always created via .

Note that the Named Constructor Idiom, at least as implemented above, is just as fast as directly calling a constructor — modern compilers will not make any extra copies of your object.

Does return-by-value mean extra copies and extra overhead?

Not necessarily.

All(?) commercial-grade compilers optimize away the extra copy, at least in cases as illustrated in the previous FAQ.

To keep the example clean, let’s strip things down to the bare essentials. Suppose function calls (“rbv” stands for “return by value”) which returns a object by value:

Now the question is, How many objects will there be? Will create a temporary object that gets copy-constructed into ? How many temporaries? Said another way, does return-by-value necessarily degrade performance?

The point of this FAQ is that the answer is No, commercial-grade C++ compilers implement return-by-value in a way that lets them eliminate the overhead, at least in simple cases like those shown in the previous FAQ. In particular, all(?) commercial-grade C++ compilers will optimize this case:

Certainly the compiler is allowed to create a temporary, local object, then copy-construct that temporary into variable within , then destruct the temporary. But all(?) commercial-grade C++ compilers won’t do that: the statement will directly construct itself. Not a copy of , not a pointer to , not a reference to , but itself.

You can stop here if you don’t want to genuinely understand the previous paragraph, but if you want to know the secret sauce (so you can, for example, reliably predict when the compiler can and cannot provide that optimization for you), the key is to know that compilers usually implement return-by-value using pass-by-pointer. When calls , the compiler secretly passes a pointer to the location where is supposed to construct the “returned” object. It might look something like this (it’s shown as a rather than a since the object has not yet been constructed):

So the first ingredient in the secret sauce is that the compiler (usually) transforms return-by-value into pass-by-pointer. This means that commercial-grade compilers don’t bother creating a temporary: they directly construct the returned object in the location pointed to by .

The second ingredient in the secret sauce is that compilers typically implement constructors using a similar technique. This is compiler-dependent and somewhat idealized (I’m intentionally ignoring how to handle and overloading), but compilers typically implement using something like this:

Putting these together, the compiler might implement the statement in by simply passing as the constructor’s pointer:

So passes to , and in turn passes to the constructor (as the pointer). That means constructor directly constructs .

In the early 90s I did a seminar for IBM’s compiler group in Toronto, and one of their engineers told me that they found this return-by-value optimization to be so fast that you get it even if you don’t compile with optimization turned on. Because the return-by-value optimization causes the compiler to generate less code, it actually improves compile-times in addition to making your generated code smaller and faster. The point is that the return-by-value optimization is almost universally implemented, at least in code cases like those shown above.

Final thought: this discussion was limited to whether there will be any extra copies of the returned object in a return-by-value call. Don’t confuse that with other things that could happen in . For example, if you changed from to (note the after the declaration), the compiler is required to use ’s assignment operator, and unless the compiler can prove that ’s default constructor followed by assignment operator is exactly the same as its copy constructor, the compiler is required by the language to put the returned object into an unnamed temporary within , use the assignment operator to copy the temporary into , then destruct the temporary. The return-by-value optimization still plays its part since there will be only one temporary, but by changing to , you have prevented the compiler from eliminating that last temporary.

What about returning a local variable by value? Does the local exist as a separate object, or does it get optimized away?

When your code returns a local variable by value, your compiler might optimize away the local variable completely - zero space-cost and zero time-cost - the local variable never actually exists as a distinct object from the caller’s target variable (see below for specifics about exactly what this means). Other compilers do not optimize it away.

These are some(!) of the compilers that optimize away the local variable completely:

  • GNU C++ (g++) since at least version 3.3.3
  • (Others need to be added; need more info)

These are some(!) of the compilers that do not optimize away the local variable:

  • Microsoft Visual C++.NET 2003
  • (Others need to be added; need more info)

Here is an example showing what we mean in this FAQ:

The question addressed in this FAQ is this: How many objects actually get created in the runtime system? Conceptually there could be as many as three distinct objects: the temporary created by , variable (in ), and variable (in ). However as we saw earlier most compilers merge and variable into the same object, reducing the total number of objects from 3 to 2. But this FAQ pushes it one step further: does (in ) show up as a distinct, runtime object from (in )?

Some compilers, including but not limited to those listed above, completely optimize away local variable . In those compilers, there is only one object in the above code: ’s variable is exactly identically the same object as ’s variable .

They do this the same way as described earlier: the return-by-value in function is implemented as pass-by-pointer, where the pointer points to the location where the returned object is to be initialized.

So instead of constructing as a local object, these compilers simply construct , and everytime they see variable used in the original source code, they substitute instead. Then the line becomes simply since the returned object has already been constructed in the location designated by the caller.

Here is the resulting (pseudo)code:

Caveat: this optimization can be applied only when all a function’s statements return the same local variable. If one statement in returned local variable but another returned something else, such as a global or a temporary, the compiler could not alias the local variable into the caller’s destination, . Verifying that all the function’s return statements return the same local variable requires extra work on the part of the compiler writers, which is usually why some compilers fail to implement that return-local-by-value optimization.

Final thought: this discussion was limited to whether there will be any extra copies of the returned object in a return-by-value call. Don’t confuse that with other things that could happen in . For example, if you changed from to (note the after the declaration), the compiler is required to use ’s assignment operator, and unless the compiler can prove that ’s default constructor followed by assignment operator is exactly the same as its copy constructor, the compiler is required by the language to put the returned object into an unnamed temporary within , use the assignment operator to copy the temporary into , then destruct the temporary. The return-by-value optimization still plays its part since there will be only one temporary, but by changing to , you have prevented the compiler from eliminating that last temporary.

Why can’t I initialize my member data in my constructor’s initialization list?

Because you must explicitly define your class’s data members.


(or or whatever):

Note: in some cases, the definition of might not contain the initializer part. For details, see here and here.

Why are classes with data members getting linker errors?

Because data members must be explicitly defined in exactly one compilation unit. If you didn’t do this, you’ll probably get an linker error. For example:

The linker will holler at you () unless you define (as opposed to merely declare) in (exactly) one of your source files:

The usual place to define data members of is file (or or whatever source file extension you use).

Note: in some cases, you can add initializer to the declaration of class-scope declarations, however if you ever use the data member, you still need to explicitly define it in exactly one compilation unit. In this case you don’t include an initializer in the definition. A separate FAQ covers this topic.

Can I add initializer to the declaration of a class-scope data member?

Yes, though with some important caveats.

Before going through the caveats, here is a simple example that is allowed:

And, just like other data members, it must be defined in exactly one compilation unit, though this time without the initializer part:

The caveats are that you may do this only with integral or enumeration types, and that the initializer expression must be an expression that can be evaluated at compile-time: it must only contain other constants, possibly combined with built-in operators. For example, is a compile-time constant expression, as is provided and are compile-time constants. After the declaration above, is also a compile-time constant: it can be used in other compile-time constant expressions.

If you ever take the address of , such as passing it by reference or explicitly saying , the compiler will make sure it has a unique address. If not, won’t even take up space in your process’s static data area.

What’s the “ initialization order fiasco”?

A subtle way to crash your program.

The initialization order fiasco is a very subtle and commonly misunderstood aspect of C++. Unfortunately it’s very hard to detect — the errors often occur before begins.

In short, suppose you have two objects and which exist in separate source files, say and . Suppose further that the initialization for the object (typically the object’s constructor) calls some method on the object.

That’s it. It’s that simple.

The tragedy is that you have a 50%-50% chance of dying. If the compilation unit for happens to get initialized first, all is well. But if the compilation unit for get initialized first, then ’s initialization will get run before ’s initialization, and you’re toast. E.g., ’s constructor could call a method on the object, yet the object hasn’t yet been constructed.

I hear they’re hiring down at McDonalds. Enjoy your new job flipping burgers.

If you think it’s “exciting” to play Russian Roulette with live rounds in half the chambers, you can stop reading here. On the other hand if you like to improve your chances of survival by preventing disasters in a systematic way, you probably want to read the next FAQ.

Note: The static initialization order fiasco can also, in some cases, apply to built-in/intrinsic types.

How do I prevent the “ initialization order fiasco”?

To prevent the static initialization order fiasco, use the Construct On First Use Idiom, described below.

The basic idea of the Construct On First Use Idiom is to wrap your object inside a function. For example, suppose you have two classes, and . There is a namespace-scope / global object called , and a namespace-scope / global object called . ’s constructor invokes the method on the object. The file defines the object:

The file defines the object:

For completeness the constructor might look something like this:

You would have a initialization disaster if got constructed before . As written above, this disaster would occur roughly 50% of the time, since the two objects are declared in different source files and those source files give no hints to the compiler or linker as to the order of static initialization.

There are many solutions to this problem, but a very simple and completely portable solution is the Construct On First Use Idiom: replace the namespace-scope / global object with a namespace-scope / global function that returns the object by reference.

Since local objects are constructed the first time control flows over their declaration (only), the above statement will only happen once: the first time is called. Every subsequent call will return the same object (the one pointed to by ). Then all you do is change your usages of to :

This is called the Construct On First Use Idiom because it does just that: the (logically namespace-scope / global) object is constructed on its first use.

The downside of this approach is that the object is never destructed. If the object has a destructor with important side effects, there is another technique that answers this concern; but it needs to be used with care since it creates the possibility of another (equally nasty) problem.

Note: The static initialization order fiasco can also, in some cases, apply to built-in/intrinsic types.

Why doesn’t the Construct On First Use Idiom use a object instead of a pointer?

Short answer: it’s possible to use a static object rather than a static pointer, but doing so opens up another (equally subtle, equally nasty) problem.

Long answer: sometimes people worry about the fact that the previous solution “leaks.” In many cases, this is not a problem, but it is a problem in some cases. Note: even though the object pointed to by in the previous FAQ is never deleted, the memory doesn’t actually “leak” when the program exits since the operating system automatically reclaims all the memory in a program’s heap when that program exits. In other words, the only time you’d need to worry about this is when the destructor for the object performs some important action (such as writing something to a file) that must occur sometime while the program is exiting.

In those cases where the construct-on-first-use object (the , in this case) needs to eventually get destructed, you might consider changing function as follows:

However there is (or rather, may be) a rather subtle problem with this change. To understand this potential problem, let’s remember why we’re doing all this in the first place: we need to make 100% sure our static object (a) gets constructed prior to its first use and (b) doesn’t get destructed until after its last use. Obviously it would be a disaster if any static object got used either before construction or after destruction. The message here is that you need to worry about two situations (static initialization and static deinitialization), not just one.

By changing the declaration from to , we still correctly handle the initialization situation but we no longer handle the deinitialization situation. For example, if there are 3 static objects, say , and , that use during their destructors, the only way to avoid a static deinitialization disaster is if is destructed after all three.

The point is simple: if there are any other static objects whose destructors might use after is destructed, bang, you’re dead. If the constructors of , and use , you should normally be okay since the runtime system will, during static deinitialization, destruct after the last of those three objects is destructed. However if and/or and/or fail to use in their constructors and/or if any code anywhere gets the address of and hands it to some other static object, all bets are off and you have to be very, very careful.

There is a third approach that handles both the static initialization and static deinitialization situations, but it has other non-trivial costs.

What is a technique to guarantee both initialization and deinitialization?

Short answer: use the Nifty Counter Idiom (but make sure you understand the non-trivial tradeoffs!).


  • The Construct On First Use Idiom uses a pointer and intentionally leaks the object. That is often innocuous, since the operating system will typically clean up a process’s memory when the process terminates. However if the object has a non-trivial destructor with important side effects, such as writing to a file or some other non-volatile action, then you need more.
  • That’s where the second version of the Construct On First Use Idiom came in: it doesn’t leak the object, but it does not control the order of static deinitialization, so it is (very!) unsafe to use the object during static deinitialization, that is, from a destructor of another statically declared object.
  • If you need to control the order of both static initialization and static deinitialization, meaning if you wish to access a statically allocated object from both constructors and destructors of other static objects, then keep reading.
  • Otherwise run away.


TODO: WRITE UP TRADEOFFS — now that you know how to use the Nifty Counter Idiom, be sure you understand both when and (especially!) when not to use it! One size does not fit all.

How do I prevent the “ initialization order fiasco” for my data members?

Use the Construct Members On First Use Idiom, which is basically the same as the regular Construct On First Use Idiom, or perhaps one of its variants, but it uses a member function instead of a namespace-scope / global function.

Suppose you have a class that has a object:

Naturally this member is initialized separately:

Naturally also the object will be used in one or more of ’s methods:

But now the “disaster scenario” is if someone somewhere somehow calls this method before the object gets constructed. For example, if someone else creates a static object and invokes its method during initialization, then you’re at the mercy of the compiler as to whether the compiler will construct before or after the is called. (Note that the ANSI/ISO C++ committee is working on this problem, but compilers aren’t yet generally available that handle these changes; watch this space for an update in the future.)

In any event, it’s always portable and safe to change the data member into a member function:

Naturally this member is initialized separately:

Then you simply change any usages of to :

If you’re super performance sensitive and you’re concerned about the overhead of an extra function call on each invocation of you can set up a instead. As you recall, local are only initialized once (the first time control flows over their declaration), so this will call only once: the first time is called:

Note: The static initialization order fiasco can also, in some cases, apply to built-in/intrinsic types.

Do I need to worry about the “ initialization order fiasco” for variables of built-in/intrinsic types?


If you initialize your built-in/intrinsic type using a function call, the static initialization order fiasco is able to kill you just as bad as with user-defined/class types. For example, the following code shows the failure:

The output of this little program will show that it uses before initializing it. The solution, as before, is the Construct On First Use Idiom:

Of course you might be able to simplify this by moving the initialization code for and into their respective functions:

And, if you can get rid of the print statements you can further simplify these to something really simple:

Furthermore, since is initialized using a constant expression, it no longer needs its wrapper function — it can be a simple variable again.

How can I handle a constructor that fails?

Throw an exception. For details, see here.

What is the “Named Parameter Idiom”?

It’s a fairly useful way to exploit method chaining.

The fundamental problem solved by the Named Parameter Idiom is that C++ only supports positional parameters. For example, a caller of a function isn’t allowed to say, “Here’s the value for formal parameter , and this other thing is the value for formal parameter .” All you can do in C++ (and C and Java) is say, “Here’s the first parameter, here’s the second parameter, etc.” The alternative, called named parameters and implemented in the language Ada, is especially useful if a function takes a large number of mostly default-able parameters.

Over the years people have cooked up lots of workarounds for the lack of named parameters in C and C++. One of these involves burying the parameter values in a string parameter then parsing this string at run-time. This is what’s done in the second parameter of , for example. Another workaround is to combine all the boolean parameters in a bit-map, then the caller or’s a bunch of bit-shifted constants together to produce the actual parameter. This is what’s done in the second parameter of , for example. These approaches work, but the following technique produces caller-code that’s more obvious, easier to write, easier to read, and is generally more elegant.

The idea, called the Named Parameter Idiom, is to change the function’s parameters to methods of a newly created class, where all these methods return by reference. Then you simply rename the main function into a parameterless “do-it” method on that class.

We’ll work an example to make the previous paragraph easier to understand.

The example will be for the “open a file” concept. Let’s say that concept logically requires a parameter for the file’s name, and optionally allows parameters for whether the file should be opened read-only vs. read-write vs. write-only, whether or not the file should be created if it doesn’t already exist, whether the writing location should be at the end (“append”) or the beginning (“overwrite”), the block-size if the file is to be created, whether the I/O is buffered or non-buffered, the buffer-size, whether it is to be shared vs. exclusive access, and probably a few others. If we implemented this concept using a normal function with positional parameters, the caller code would be very difficult to read: there’d be as many as 8 positional parameters, and the caller would probably make a lot of mistakes. So instead we use the Named Parameter Idiom.

Before we go through the implementation, here’s what the caller code might look like, assuming you are willing to accept all the function’s default parameters:

That’s the easy case. Now here’s what it might look like if you want to change a bunch of the parameters.

Notice how the “parameters”, if it’s fair to call them that, are in random order (they’re not positional) and they all have names. So the programmer doesn’t have to remember the order of the parameters, and the names are (hopefully) obvious.

So here’s how to implement it: first we create a class () that houses all the parameter values as data members. The required parameters (in this case, the only required parameter is the file’s name) is implemented as a normal, positional parameter on ’s constructor, but that constructor doesn’t actually open the file. Then all the optional parameters (readonly vs. readwrite, etc.) become methods. These methods (e.g., , , etc.) return a reference to their object so the method calls can be chained.

The only other thing to do is make the constructor for class to take an object:

This constructor gets the actual parameters from the OpenFile object, then actually opens the file:

Note that declares as its , that way doesn’t need a bunch of (otherwise useless) get methods.

Since each member function in the chain returns a reference, there is no copying of objects and the chain is highly efficient. Furthermore, if the various member functions are , the generated object code will probably be on par with C-style code that sets various members of a . Of course if the member functions are not , there may be a slight increase in code size and a slight decrease in performance (but only if the construction occurs on the critical path of a CPU-bound program; this is a can of worms I’ll try to avoid opening), so it may, in this case, be a tradeoff for making the code more reliable.

Why am I getting an error after declaring a object via ?

Because that doesn’t create a object - it declares a non-member function that returns a object. The term “Most Vexing Parse” was coined by Scott Myers to describe this situation.

This is really going to hurt; you might want to sit down.

First, here’s a better explanation of the problem. Suppose there is a class called that has a default ctor. This might even be a library class such as , but for now we’ll just call it :

Now suppose there’s another class called that has a ctor that takes a . As before, this might be defined by someone other than you.

Now you want to create a object using a temporary . In other words, you want to create an object via , and pass that to the ctor to create a local object called :

It’s a long story, but one solution (hope you’re sitting down!) is to add an extra pair of s around the part:

Another solution is to use in your declaration (see the fine print below):

Note: The above solution requires to be able to access the copy constructor. In most situations that means the copy constructor needs to be , though it needn’t be in the less common case where is a friend of . If you’re not sure what any of that means, try it: if your code compiles, you passed the test.

Here’s another solution (more fine print below):

Note: The word “usually” in the above means this: the above fails only when constructor is , or when ’s copy constructor is inaccessible (typically when it is or , and your code is not a ). If you’re not sure what any of that means, take 60 seconds and compile it. You are guaranteed to find out whether it works or fails at compile-time, so if it compiles cleanly, it will work at runtime.

However, the best solution, the creation of which was at least partially motivated by the fact that this FAQ exists, is to use uniform initialization, which replaces the around the call with instead.

That’s the end of the solutions; the rest of this is about why this is needed (this is optional; you can skip this section if you don’t care enough about your career to actually understand what’s going on; ha ha): When the compiler sees , it thinks that the part is declaring a non-member function that returns a object, so it thinks you are declaring the existence of a function called that returns a and that takes as a single parameter of type “non-member function that takes nothing and returns a .”

Now here’s the sad part. In fact it’s pathetic. Some mindless drone out there is going to skip that last paragraph, then they’re going to impose a bizarre, incorrect, irrelevant, and just plain stupid coding standard that says something like, “Never create temporaries using a default constructor” or “Always use in all initializations” or something else equally inane. If that’s you, please fire yourself before you do any more damage. Those who don’t understand the problem shouldn’t tell others how to solve it. Harumph.

(That was mostly tongue in cheek. But there’s a grain of truth in it. The real problem is that people tend to worship consistency, and they tend to extrapolate from the obscure to the common. That’s not wise.)

What is the purpose of the keyword?

The keyword is an optional decoration for constructors and conversion operators to tell the compiler that a certain constructor or conversion operator may not be used to implicitly cast an expression to its class type.

For example, without the keyword the following code is valid:

But sometimes you want to prevent this sort of implicit promotion or implicit type conversion. For example, if is really an array-like container and 42 is the initial size, you might want to let your users say, or perhaps , but not just . If that’s the case, you should use the keyword:

You can mix and non- constructors and conversion operators in the same class. For example, this class has an constructor taking a but a non- constructor taking a , and can be implicitly converted to double, but only explicitly converted to bool:

The above code will print the following:

Variable is initialized using the constructor because cannot be used in an implicit cast, but can be interpreted as a , that is, as , and implicitly cast to using . This may or may not be what you intended, but this is what happens.

Why doesn’t my constructor work right?

This is a question that comes in many forms. Such as:

  • Why does the compiler copy my objects when I don’t want it to?
  • How do I turn off copying?
  • How do I stop implicit conversions?
  • How did my int turn into a complex number?

By default a class is given a copy constructor and a copy assignment that copy all elements, and a move constructor and a move assignment that move all elements. For example:

Here we get and . That’s often exactly what you want (and essential for C compatibility), but consider:

Here, the default copy gives us and . This leads to disaster: when we exit the destructors for and are invoked and the object pointed to by and is deleted twice.

How do we avoid this? The simplest solution is to mark the operations that copy as deleted:

If we need to copy or move, we can of course define the proper initializers and assignments to provide the desired semantics.

Now return to . For the default copy semantics is fine, the problem is the constructor:

People provide default arguments to get the convenience used for and . Then, some are surprised by the conversion of to in the call of . This constructor defines a conversion. By default that’s an implicit conversion. To require such a conversion to be explicit, declare the constructor :

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:

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:

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.
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.
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:

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.

-) 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.

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
Topic archived. No new replies allowed.

0 thoughts on “C++ Initialization List Vs Assignments”


Leave a Comment

Your email address will not be published. Required fields are marked *