Following are such cases:. Consider the following example:. Here compiler follows following steps to create an object of type MyClass 1. With the Initializer List, following steps are followed by compiler: 1.
See this post for a running example on this point. Thanks to ptr for adding this point. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. This article is attributed to GeeksforGeeks. Point t1 10, 15 ;. Test t1 10 ;. For Business. For Educators. Become an Affiliate. Terms of Service. Business Terms of Service. Careers Hiring. For Bootcamps. Blog for Business. Quality Commitment. 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. The above code example can be rewritten using initializer list, and will execute smoothly without any error. If you have a data member as reference type, you must initialize it in the initialization list. References are immutable hence they can be initialized only once.
If you are assigning the values inside the body of the constructor, then a temporary object would be created which will be provided to the assignment operator. The temporary object will be destroyed at the end of the assignment statement. Creation of temporary object can be avoided by using initializer list.
0コメント