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...
};
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) ?
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.
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.
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 ofint
s.
...and was nervous a hyperactive moderator might delete it, so here it is in relative safety. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With