+ 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".
5 Réponses
+ 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 }
+ 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;
}
+ 1
DavX Thank you so much, so, can't I do this when my array is allocated on the heap ?
+ 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;
}
+ 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 👍