+ 1

Anyone knows anyway to initialize an array using member-initializer list ?

I want to initialize an array using member-initializer list, but it doesn't seem to be legal to do so : class Solution { public: Solution (int a, int b) : args[0](a), args[1](b) { } private: int* args = new int[2]; }; Besides, I guess I can only initialize the first place of my array, but not the others : Solution (int a, int b) : args(&a) { } In case I attempt to initialize next places of my array, it raises such an error : "too many initializer values".

20th Feb 2023, 8:18 PM
Ali_combination
Ali_combination - avatar
5 Respostas
+ 2
…formatting going a bit skewy with copying… I didn’t include in the example but you would want to add a destructor to clean up after (avoid any memory leaks): ~Solution() { delete[] args }
21st Feb 2023, 1:25 PM
DavX
DavX - avatar
+ 1
Ali, In C11+ you can initialize an array through member initialization list like this: #include <iostream> class Solution { private: int args[2]; public: Solution(int a, int b) : args{a, b} {} void printArr() { for (auto v : args) { std::cout << v << std::endl; } } }; int main() { Solution s1(2, 10); s1.printArr(); return 0; }
20th Feb 2023, 10:14 PM
DavX
DavX - avatar
+ 1
DavX Thank you so much, so, can't I do this when my array is allocated on the heap ?
21st Feb 2023, 7:55 AM
Ali_combination
Ali_combination - avatar
+ 1
Hi Ali, No problem, you could try this: #include <iostream> class Solution { private: int* args = nullptr; public: Solution(int a, int b) : args(new int[2]{a,b}) {} void printArgs() { for (auto i = 0; i < 2; i++) std::cout << args[i] << std::endl; } }; int main() { Solution s1(2, 10); s1.printArgs(); return 0; }
21st Feb 2023, 12:37 PM
DavX
DavX - avatar
+ 1
DavX Hello DavX Now I'm learning new things, that's exactly what I need, and your last point (avoiding memory leaks) is of course crucial. Thank you so much 👍
21st Feb 2023, 2:55 PM
Ali_combination
Ali_combination - avatar