7

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);
0

2 Answers 2

10

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) {};
};
Sign up to request clarification or add additional context in comments.

2 Comments

This class breaks the rule of 0/3/5. And why not use a std::unique_ptr<double[]>. Or more simply a std::vector.
@MikeVine Just added the alternative. ;)
4

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*/
    };
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.