#include <iostream>
#include <initializer_list>
class MyArray {
int* array;
public:
MyArray(){}
MyArray(std::initializer_list<int>& v) {
array = new int[v.size()];
int index = 0;
for (auto element : v) {
array[index] = element;
index++;
}
}
~MyArray()
{
delete[] array;
}
};
int main() {
MyArray object{ 2,4,2,2 };
}
This is my first time working with std::initializer for object list initialization. I have created a an array that is initialized using the MyArray constructor. i don't know where am i going wrong. i created an object that matches the argument list, ie a constructor that takes an initializer list.
i created an object that matches the argument list, ie a constructor that takes an initializer list.
You didn't; not quite.
You created a constructor that takes a reference to an std::initializer_list.
But one created in this manner is [possibly] a temporary that cannot bind to such a reference.
Generally you just want to take std::initializer_lists by value. That is: remove the &.
There are some examples on cppreference's article on std::initializer_list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With