In my previous article about the latest C++11 standard I talked about automatic type detection and keyword decltype
Today I will take another major enhancement in C++11 called the Initializer List or Uniform Initialization Syntax.
Let us first see the user pain points this feature is trying to resolve :
Till now C++ has multiple ways to initialize objects, for example:
1. The conventional way
int x = 10; std::string str = "mcn";
2. The constructor way
int x(10); std::string str("mcn"); int x = int(); // default constructor
3. The C language way of initializer list
int arr[] = {1,2,3,4,5}; struct Student { std::string name; int rollno; }; Student a = {"Kamal", 5};
4. The Member Initialization list of constructors
// Keping struct (and not class) for convenience // default members of struct are public. struct Student { std::string name; int rollno; Student():name(""), rollno(-1){} // default values Student(_name, _rollno) : name(_name), rollno(_rollno){} };
The multiple ways of initialization possible is a source of confusion. Plus there is no way to initialize the POD (Plain Old Data) arrays allocated memory on heap using new[].
int *ptr = new int[10]; // Cannot initialize the array in such cases
struct MyClass { MyClass(std::initializer_list); };
Than I can pass the initializer list of int which initializing the object of MyClass, as shown below:
MyClass obj = {1,2,3,4}; MyClass obj2 = {1,2,3}; MyClass obj3 = {1};
This initializer_list has made the initialization easy and uniform for developer. consider the below examples:
class MCN { int a; int b; public: MCN(int i, int j); // constructor };
The objects of MCN can be created like below:
MCN obj {0 , 1}; // Same as MCN obj(0,1);
or, on heap
int * ptr = new int[5] {1,2,3,4,5};
or, in the member initialization list like
struct MCN { int arr[3]; MCN() : arr{1,2,3} {} };
vector class in C++11 Template Library will have a constructor which will take initializer_list for its template type as below:
std:vector<int> v {1, 2, 3, 4};
Please let me know your feedbacks / comments / suggestions
Previous: Automatic type detection and decltype
Next: Range based for loop similar to for-each
4 Comments
[…] articles about C++11 standard I talked about automatic type detection , decltype keyword and uniform initializer list introduced in C++11. Lets see the Range-based for loop […]
[…] 262012 In my earlier articles on C++, I have written about the automatic type detection, uniform initialization list and Range based for loopin […]
[…] Next: Uniform initializer list in C++11 Posted by krawat Tagged with: C++11, decltype […]
Hi to every one, the contents existing at this web site are genuinely remarkable
for people knowledge, well, keep up the nice work fellows.