cppreference.com

Search

Initializer list

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

[ edit ] Syntax

[ edit ] 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

[ edit ] Example

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • This page was last modified on 15 June 2012, at 14:12.
  • This page has been accessed 331 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Initializer list

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

[ edit ] Syntax

[ edit ] 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

[ edit ] Example

Learn C++

14.10 — Constructor member initializer lists

This lesson continues our introduction of constructors from lesson 14.9 -- Introduction to constructors .

Member initialization via a member initialization list

To have a constructor initialize members, we do so using a member initializer list (often called a “member initialization list”). Do not confuse this with the similarly named “initializer list” that is used to initialize aggregates with a list of values.

Member initialization lists are something that is best learned by example. In the following example, our Foo(int, int) constructor has been updated to use a member initializer list to initialize m_x , and m_y :

The member initializer list is defined after the constructor parameters. It begins with a colon (:), and then lists each member to initialize along with the initialization value for that variable, separated by a comma. You must use a direct form of initialization here (preferably using braces, but parentheses works as well) -- using copy initialization (with an equals) does not work here. Also note that the member initializer list does not end in a semicolon.

This program produces the following output:

When foo is instantiated, the members in the initialization list are initialized with the specified initialization values. In this case, the member initializer list initializes m_x to the value of x (which is 6 ), and m_y to the value of y (which is 7 ). Then the body of the constructor runs.

When the print() member function is called, you can see that m_x still has value 6 and m_y still has value 7 .

Member initializer list formatting

C++ provides a lot of freedom to format your member initializer lists as you prefer, as it doesn’t care where you put your colon, commas, or whitespace.

The following styles are all valid (and you’re likely to see all three in practice):

Our recommendation is to use the third style above:

  • Put the colon on the line after the constructor name, as this cleanly separates the member initializer list from the function prototype.
  • Indent your member initializer list, to make it easier to see the function names.

If the member initialization list is short/trivial, all initializers can go on one line:

Otherwise (or if you prefer), each member and initializer pair can be placed on a separate line (starting with a comma to maintain alignment):

Member initialization order

Because the C++ standard says so, the members in a member initializer list are always initialized in the order in which they are defined inside the class (not in the order they are defined in the member initializer list).

In the above example, because m_x is defined before m_y in the class definition, m_x will be initialized first (even if it is not listed first in the member initializer list).

Because we intuitively expect variables to be initialized left to right, this can cause subtle errors to occur. Consider the following example:

In the above example, our intent is to calculate the larger of the initialization values passed in (via std::max(x, y) and then use this value to initialize both m_x and m_y . However, on the author’s machine, the following result is printed:

What happened? Even though m_y is listed first in the member initialization list, because m_x is defined first in the class, m_x gets initialized first. And m_x gets initialized to the value of m_y , which hasn’t been initialized yet. Finally, m_y gets initialized to the greater of the initialization values.

To help prevent such errors, members in the member initializer list should be listed in the order in which they are defined in the class. Some compilers will issue a warning if members are initialized out of order.

Best practice

Member variables in a member initializer list should be listed in order that they are defined in the class.

It’s also a good idea to avoid initializing members using the value of other members (if possible). That way, even if you do make a mistake in the initialization order, it shouldn’t matter because there are no dependencies between initialization values.

Member initializer list vs default member initializers

Members can be initialized in a few different ways:

  • If a member is listed in the member initializer list, that initialization value is used
  • Otherwise, if the member has a default member initializer, that initialization value is used
  • Otherwise, the member is default initialized.

This means that if a member has both a default member initializer and is listed in the member initializer list for the constructor, the member initializer list value takes precedence.

Here’s an example showing all three initialization methods:

On the author’s machine, this output:

Here’s what’s happening. When foo is constructed, only m_x appears in the member initializer list, so m_x is first initialized to 6 . m_y is not in the member initialization list, but it does have a default member initializer, so it is initialized to 2 . m_z is neither in the member initialization list, nor does it have a default member initializer, so it is default initialized (which for fundamental types, means it is left uninitialized). Thus, when we print the value of m_z , we get undefined behavior.

Constructor function bodies

The bodies of constructors functions are most often left empty. This is because we primarily use constructor for initialization, which is done via the member initializer list. If that is all we need to do, then we don’t need any statements in the body of the constructor.

However, because the statements in the body of the constructor execute after the member initializer list has executed, we can add statements to do any other setup tasks required. In the above examples, we print something to the console to show that the constructor executed, but we could do other things like open a file or database, allocate memory, etc…

New programmers sometimes use the body of the constructor to assign values to members:

Although in this simple case this will produce the expected result, in case where members are required to be initialized (such as for data members that are const or references) assignment will not work.

Prefer using the member initializer list to initialize your members over assigning values in the body of the constructor.

Question #1

Write a class named Ball. Ball should have two private member variables, one to hold a color, and one to hold a radius. Also write a function to print out the color and radius of the ball.

The following sample program should compile:

and produce the result:

Show Solution

Question #2

Why did we make print() a non-member function instead of a member function?

The rationale for this is given in lesson 14.8 -- The benefits of data hiding (encapsulation) .

Question #3

Why did we make m_color a std::string instead of a std::string_view ?

In this particular example, it doesn’t matter (because our color arguments are C-style string literals, which doesn’t go out of scope).

But conceptually, we want our Ball class to be an owner of the color passed in. If m_color were a std::string_view , passing in a temporary object for the color argument (e.g. a std::string returned from a function) would leave m_color dangling when the temporary color argument was destroyed.

We discuss this case in more detail (and show an example) in lesson 13.11 -- Struct miscellany .

guest

C Data Types

C operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C
  • Const Qualifier in C
  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Relational Operators in C
  • Bitwise Operators in C
  • C Logical Operators

Assignment Operators in C

  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

  • C Structures
  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C Preprocessor Directives
  • How a Preprocessor works in C?
  • Header Files in C
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C
  • _Generics Keyword in C
  • Multithreading in C
  • C Programming Interview Questions (2024)
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

c assignment operator initializer list

Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example:

2. “+=” : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a += 6) = 11.

3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the right from the current value of the variable on left and then assigns the result to the variable on the left. Example:

If initially value stored in a is 8. Then (a -= 6) = 2.

4. “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a *= 6) = 30.

5. “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

Please Login to comment...

Similar reads.

  • C-Operators
  • cpp-operator

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Constructors and member initializer lists

Constructor is a special non-static member function of a class that is used to initialize objects of its class type.

In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual base subobjects and non-static data members. ( Not to be confused with std::initializer_list )

Constructors are declared using member function declarators of the following form:

Where class-name must name the current class (or current instantiation of a class template), or, when declared at namespace scope or in a friend declaration, it must be a qualified class name.

The only specifiers allowed in the decl-specifier-seq of a constructor declaration are friend , inline , explicit and constexpr (in particular, no return type is allowed). Note that cv- and ref-qualifiers are not allowed either; const and volatile semantics of an object under construction don't kick in until the most-derived constructor completes.

The body of a function definition of any constructor, before the opening brace of the compound statement, may include the member initializer list , whose syntax is the colon character : , followed by the comma-separated list of one or more member-initializers , each of which has the following syntax

Explanation

Constructors have no names and cannot be called directly. They are invoked when initialization takes place, and they are selected according to the rules of initialization. The constructors without explicit specifier are converting constructors . The constructors with a constexpr specifier make their type a LiteralType . Constructors that may be called without any argument are default constructors . Constructors that take another object of the same type as the argument are copy constructors and move constructors .

Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified. For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified. No initialization is performed for anonymous unions or variant members that do not have a member initializer.

The initializers where class-or-identifier names a virtual base class are ignored during execution of constructors of any class that is not the most derived class of the object that's being constructed.

Names that appear in expression-list or brace-init-list are evaluated in scope of the constructor:

Exceptions that are thrown from member initializers may be handled by function-try-block

Member functions (including virtual member functions) can be called from member initializers, but the behavior is undefined if not all direct bases are initialized at that point.

For virtual calls (if the bases are initialized), the same rules apply as the rules for the virtual calls from constructors and destructors: virtual member functions behave as if the dynamic type of * this is the class that's being constructed (dynamic dispatch does not propagate down the inheritance hierarchy) and virtual calls (but not static calls) to pure virtual member functions are undefined behavior.

Initialization order

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

(Note: if initialization order was controlled by the appearance in the member initializer lists of different constructors, then the destructor wouldn't be able to ensure that the order of destruction is the reverse of the order of construction)

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

  • C++11 standard (ISO/IEC 14882:2011):
  • 12.1 Constructors [class.ctor]
  • 12.6.2 Initializing bases and members [class.base.init]
  • C++98 standard (ISO/IEC 14882:1998):

IMAGES

  1. Lexical Units (Tokens)

    c assignment operator initializer list

  2. Operators in C

    c assignment operator initializer list

  3. Assignment Operators in C

    c assignment operator initializer list

  4. Assignment Operators in C » PREP INSTA

    c assignment operator initializer list

  5. OOPS: NOTES

    c assignment operator initializer list

  6. 9.6. Constructors And Initializer Lists

    c assignment operator initializer list

VIDEO

  1. C++

  2. Modern C++ Programming #33: Class Basics 3

  3. Assignment Operator in C Programming

  4. Initializer List In C++

  5. (ARCHIVED) Learn JavaScript by Building a Role Playing Game

  6. Augmented assignment operators in C

COMMENTS

  1. std::initializer_list

    An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T (that may be allocated in read-only memory). a brace-enclosed initializer list is bound to auto, including in a ranged for loop . std::initializer_list may be implemented as a pair of pointers or pointer and length.

  2. c++

    Unlike auto, where a braced-init-list is deduced as an initializer_list, template argument deduction considers it to be a non-deduced context, unless there exists a corresponding parameter of type initializer_list<T>, in which case the T can be deduced.. From §14.8.2.1/1 [temp.deduct.call] (emphasis added). Template argument deduction is done by comparing each function template parameter type ...

  3. When do we use Initializer List in C++?

    Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class. Example. C++.

  4. 23.7

    Class assignment using std::initializer_list. You can also use std::initializer_list to assign new values to a class by overloading the assignment operator to take a std::initializer_list parameter. This works analogously to the above. We'll show an example of how to do this in the quiz solution below.

  5. Constructors and member initializer lists

    Constructors and member initializer lists. Constructor is a special non-static member function of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual base subobjects and non-static data members.

  6. Initializer list

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

  7. 1.4

    1.4 — Variable assignment and initialization. Alex April 25, 2024. In the previous lesson ( 1.3 -- Introduction to objects and variables ), we covered how to define a variable that we can use to store values. In this lesson, we'll explore how to actually put values into variables and use those values. As a reminder, here's a short snippet ...

  8. std::initializer_list

    An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type T.. A std::initializer_list object is automatically constructed when: . a braced-init-list is used in list-initialization, including function-call list initialization and assignment expressions (not to be confused with constructor initializer lists)

  9. Initializer list

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

  10. 14.10

    This program produces the following output: Foo(6, 7) constructed Foo(6, 7) When foo is instantiated, the members in the initialization list are initialized with the specified initialization values. In this case, the member initializer list initializes m_x to the value of x (which is 6), and m_y to the value of y (which is 7).Then the body of the constructor runs.

  11. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current value of the variable on left to the value on the right and ...

  12. Constructors and member initializer lists

    Constructor is a special non-static member function of a class that is used to initialize objects of its class type.. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual base subobjects and non-static data members. ( Not to be confused with std::initializer_list) . Syntax. Constructors are declared using member function ...

  13. What do you prefer

    List initialisation or assignment operator? This is part of the confusion. Here the = isn't an assignment operator, but "copy initialization". It just looks like assignment. Some of us find that confusing.. So I have also started to use { } initialization wherever possible, and leave use of = to where it really is assignment. Might take a while to get used to, but now works fine.

  14. c++

    The symbol = is used for both copy-initialization and assignment, but initialization does NOT use the assignment operator. Initialization of a variable actually uses a constructor. In copy-initialization, it uses a copy constructor. type x = e; // NOT an assignment operator. First e is converted to type, creating a temporary variable, and then ...

  15. c++

    To initialize is to make ready for use. And when we're talking about a variable, that means giving the variable a first, useful value. And one way to do that is by using an assignment. So it's pretty subtle: assignment is one way to do initialization. Assignment works well for initializing e.g. an int, but it doesn't work well for initializing ...