Why member initialization list in c
Initializer list is used to initialize data members. The syntax begins with a colon : and then each variable along with its value separated by a comma. The initializer list does not end in a semicolon. The above code is just an example to understand the syntax of Initializer list.
In the above code, value can easily be initialized inside the constructor as well, hence we do not have to use initializer list. There are situations where initialization of data members inside constructor doesn't work and Initializer List must be used. Following are such cases:. In Inheritance base class constructor is called first Order of Constructor call , followed by the child class constructor.
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. Create account Log in. Namespaces Page Discussion. Views View Edit History. From cppreference. Keywords Escape sequences. Namespace declaration. Namespace aliases. Fundamental types Enumeration types Function types. Compound types Union types. Default initialization Value initialization Zero initialization Copy initialization Direct initialization.
Expressions Value categories Order of evaluation. Operators Operator precedence. Class declaration Constructors this pointer. Access specifiers friend specifier. Class template Function template. Inline assembly. Run this code. Compiler support. Freestanding and hosted. Language support library. Technical specifications. Flow control. The member initializer list is inserted after the constructor parameters.
It begins with a colon : , and then lists each variable to initialize along with the value for that variable separated by a comma. Note that we no longer need to do the assignments in the constructor body, since the initializer list replaces that functionality. Also note that the initializer list does not end in a semicolon. Of course, constructors are more useful when we allow the caller to pass in the initialization values:. Initializing array members with member initializer lists.
Initializing member variables that are classes. When variable b is constructed, the B int constructor is called with value 5. But here are some recommendations:. Change Language. Related Articles. Table of Contents. Save Article. Improve Article. Like Article. Point t1 10, 15 ;. Test t1 10 ;. Test t1 x ;.
0コメント