This
Array array = {1, 2, 3, 4};
is not initializing using a raw array. this uses an initializer list or a uniform initializer. If you want to use a raw array, you must define it firstly, like what follows.
I used templates and passing by reference to deduce the size.
#include <iostream>
#include <algorithm>
struct Array {
size_t size;
size_t capacity;
int *ptr = nullptr;
template<size_t n>
Array(int (&arr) [n]):size{n}, capacity{2*size}, ptr{ new int[capacity]}{
std::copy(std::cbegin(arr), std::cend(arr), ptr);
}
~Array(){delete[] ptr;}
};
int main(){
int arr [] = {1, 2, 3, 4};
Array array = arr;
std::for_each(array.ptr, array.ptr+array.size, [](auto el){std::cout << el << " ";});
}
Demo
And this is another approach (using the uniform initializer), if you want to initialize your class as you showed
#include <iostream>
#include <algorithm>
struct Array {
size_t size;
size_t capacity;
int *ptr = nullptr;
template<class ... Args, class = std::enable_if_t<std::is_same_v<std::common_type_t<Args...>,int>>>
Array(Args ... args):size{sizeof...(Args)}, capacity{2*size},ptr{ new int[capacity]}{
int* temp = ptr;
((*(temp++) = args),...);
}
~Array(){delete[] ptr;}
};
int main(){
Array array = {1,2,3,4};
std::for_each(array.ptr, array.ptr+array.size, [](auto el){std::cout << el << " ";});
}
Demo
Using std::initializer_list<int>, it will be
#include <iostream>
#include <algorithm>
struct Array {
size_t size;
size_t capacity;
int *ptr = nullptr;
Array(std::initializer_list<int> && ls):size{ls.size()}, capacity{2*size},ptr{ new int[capacity]}{
std::copy(ls.begin(), ls.end(), ptr);
}
~Array(){delete[] ptr;}
};
int main(){
Array array = {1,2,3,4};
std::for_each(array.ptr, array.ptr+array.size, [](auto el){std::cout << el << " ";});
}
Demo
std::arrayorstd::vectorstd::vectoris open source, so study its source code.ptrshould better be initialialized withnewand destroyed withdelete