Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array constructor for my class?

Tags:

c++

arrays

c++11

I would like to create a constructor, which is similar to the int array constructor: int foo[3] = { 4, 5, 6 };

But I would like to use it like this:

MyClass<3> foo = { 4, 5, 6 };

There is a private n size array in my class:

template<const int n=2>
class MyClass {

    public:

        // code...

    private:

        int numbers[n];

        // code...

};
like image 605
Iter Ator Avatar asked Jan 15 '16 12:01

Iter Ator


People also ask

How do you assign an array to a constructor?

Use std::array for a fixed size array: #include <array> class bin_tree { private: std::array<int, 4>data; public: bin_tree() : data({1, 2, 3, 4}) { } ... }; If you need dynamic resizing, then use std::vector instead. What the point of using std::array in that particular example (instead of old-style array) ?

Can I create an array constructor in Java?

Initialize Array in Constructor in JavaWe can create an array in constructor as well to avoid the two-step process of declaration and initialization. It will do the task in a single statement. See, in this example, we created an array inside the constructor and accessed it simultaneously to display the array elements.

How do you create an array in class?

Creating an Array of Objects We can use any of the following statements to create an array of objects. Syntax: ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of objects.


1 Answers

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

MyClass(std::initializer_list<int> l)
{
    ...if l.size() != n throw / exit / assert etc....
    std::copy(l.begin(), l.end(), &numbers[0]);
}

TemplateRex commented...

You might want to warn that such constructors are very greedy and can easily lead to unwanted behavior. E.g. MyClass should not have constructors taking a pair of ints.

...and was nervous a hyperactive moderator might delete it, so here it is in relative safety. :-)

like image 178
Tony Delroy Avatar answered Oct 20 '22 22:10

Tony Delroy