Namespaces
Variants
Views
Actions

Initializer list

From cppreference.com
< cpp‎ | language
Revision as of 22:08, 2 November 2012 by P12bot (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
friend specifier
initializer lists
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

( Not to be confused with std::initializer_list ) They are the part of a constructor which is responsible for member and ancestor initialization

Syntax

Template:sparam : Template:sparam { Template:sparam }

Explanation

The initializer list is the place where initialization of the object should occur, there is where the constructors for base classes and members are called. Members are initialized in the same order as they are declared, not as they appear in the initializer list.

If a parameter in the constructor has the same name as one of the members, the ambiguity of that identifier being passed in a constructor call inside the intializer list is resolved choosing the parameter (and not the member).

Members or base classes not present in the list will be default constructed

Example

struct Class : public Base
{
    int x;
    int y;
 
    Class ( int x )
      : Base ( 123 ), // initialize base class
        x ( x ),      // x (member) is initialized with x (parameter)
        y ( 0 )       // y initialized to 0
    {}                // empty constructor body
 
    Class ( double a )
      : y ( a+1 ),
        x ( y ) // x will be initialized before y, this means that its value here is undefined
    {}          // No base class constructor in list, this is the same as calling Base()
 
    Class()
    try
      : Base ( 789 ),
        x ( 0 ),
        y ( 0 )
    {
        // no exception
    }
    catch (...)
    {
        // exception occurred on initialization
    }
};