[C++] How to initialize my class like array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

[C++] How to initialize my class like array

We usually initialize an array like this int arr[] = {0, 1, 2}; Is it possible to initialize my class using the same method as array? MyClass c = {0, 1, 2};

17th Nov 2018, 9:18 AM
左其右
左其右 - avatar
2 Answers
+ 15
Yes, it is, as you can see in the following example program: https://code.sololearn.com/cx4NS5waGYFL/?ref=app This kind of initialization is called 'Uniform Initialization'. For more information regarding this topic, have a look at the following articles: https://www.geeksforgeeks.org/uniform-initialization-in-c/ https://msdn.microsoft.com/en-us/library/dn387583.aspx This kind of initialization works only thanks to the introduction of initializer lists back in C++11. If you want to learn more about those, then you can visit some C++ references: https://en.cppreference.com/w/cpp/language/initializer_list https://de.cppreference.com/w/cpp/utility/initializer_list http://www.cplusplus.com/reference/initializer_list/initializer_list/
17th Nov 2018, 11:27 AM
Shadow
Shadow - avatar
+ 5
Thanks !!
17th Nov 2018, 2:38 PM
左其右
左其右 - avatar