Initialize a class with an array Initialize a class with an array arrays arrays

Initialize a class with an array


It is called list initialization and you need a std::initilizer_list constructor, that to be achieved in your MyClass.

#include <initializer_list>  class MyClass {    double *_v;    std::size_t _size;public:    MyClass(std::initializer_list<double> list)         :_v(nullptr), _size(list.size())    {        _v = new double[_size];        std::size_t index = 0;        for (const double element : list)        {            _v[index++] = element;        }    };    ~MyClass() { delete _v; } // never forget, what you created using `new`};int main(){    auto x = MyClass({ 1.,2.,3. }); // now you can    //or    MyClass x2{ 1.,2.,3. };    //or    MyClass x3 = { 1.,2.,3. };}

Also note that providing size_of_v in a constructor is redundant, as it can be acquired from std::initializer_list::size method.

And to completeness, follow rule of three/five/zero.


As an alternative, if you can use std::vector, this could be done in a much simpler way, in which no manual memory management would be required. Moreover, you can achieve the goal by less code and, no more redundant _size member.

#include <vector>#include <initializer_list>    class MyClass {    std::vector<double> _v;public:        MyClass(std::initializer_list<double> vec): _v(vec) {};};


Well you can use std::vector instead the double*v & it would fit perfectly for your goal

class MyClass {    MyClass(vector<double> v){        /*do something with v*/    };};