SuperMurloc
SuperMurloc

Reputation: 209

List initialisation in a class constructor in C++

I'm new to C++ and how to make constructor for a vector confused me so much. I have a class like this:

class myClass{
public:
    myClass();
    ......
private:
    std::vector<double> myVariable;
    ......
}

and I want to write a constructor for

myClass{1.2, 2.0, 3.1, 4.0};

How do I do this?

Upvotes: 0

Views: 83

Answers (2)

Swapnil
Swapnil

Reputation: 401

You can first create a vector, insert elements to it, pass it to the myClass constructor, which assigns it to the class member vector:

class myClass
{
public:
    myClass(const std::vector<double> &src)
        : myVariable(src)
    {
    }

    private:
        std::vector<double> myVariable;
};

int main()
{
    std::vector<double> myvect{1.2, 2.0, 3.1, 4.0};
    myClass obj(myvect);
}

Upvotes: 0

Jesper Juhl
Jesper Juhl

Reputation: 31447

You need a constructor that accepts a std::initializer_list:

explicit myClass(std::initializer_list<double> init) : myVariable(init) {}

Upvotes: 6

Related Questions