[c++] C++: Where to initialize variables in constructor

Possible Duplicate:
C++ initialization lists

What are the pros/cons of initializing variables at option 1 vs option 2?

class MyClass
{
public:
    MyClass( float f, char a );
private:
    float mFloat;
    char mCharacter;
    bool mBoolean;
    int mInteger;
};

MyClass::MyClass( float f, char a ) : mFloat( f ), mBoolean( true ) // option 1.
{
    // option 2
    mCharacter = a;
    mInteger = 0;
}

Edit: Why is option 2 so common?

This question is related to c++ constructor initialization

The answer is


In short, always prefer initialization lists when possible. 2 reasons:

  • If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.

  • Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.

Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.


Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.


There are many other reasons. You should always initialize all member variables in the initialization list if possible.

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6


Option 1 allows you to initialize const members. This cannot be done with option 2 (as they are assigned to, not initialized).

Why must const members be intialized in the constructor initializer rather than in its body?


See Should my constructors use "initialization lists" or "assignment"?

Briefly: in your specific case, it does not change anything. But:

  • for class/struct members with constructors, it may be more efficient to use option 1.
  • only option 1 allows you to initialize reference members.
  • only option 1 allows you to initialize const members
  • only option 1 allows you to initialize base classes using their constructor
  • only option 2 allows you to initialize array or structs that do not have a constructor.

My guess for why option 2 is more common is that option 1 is not well-known, neither are its advantages. Option 2's syntax feels more natural to the new C++ programmer.


Option 1 allows you to use a place specified exactly for explicitly initializing member variables.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to constructor

Two constructors Class constructor type in typescript? ReactJS: Warning: setState(...): Cannot update during an existing state transition Inheritance with base class constructor with parameters What is the difference between using constructor vs getInitialState in React / React Native? Getting error: ISO C++ forbids declaration of with no type undefined reference to 'vtable for class' constructor Call asynchronous method in constructor? Purpose of a constructor in Java? __init__() missing 1 required positional argument

Examples related to initialization

"error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to declare an ArrayList with values? Initialize array of strings Initializing a dictionary in python with a key value and no corresponding values Declare and Initialize String Array in VBA VBA (Excel) Initialize Entire Array without Looping Default values and initialization in Java Initializing array of structures C char array initialization