Initialize a class with an array

  • A+

I have a class like this:

class MyClass {     MyClass(double *v, int size_of_v){         /*do something with v*/     }; }; 

My question: Is there any way, I can initialize such class without defining an array of double and feeding it to the constructor?

I would like to do something like:

auto x = MyClass({1.,2.,3.}, 3); 


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) {}; }; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: