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);
Initializing an array In order to store values in the array, we must initialize it first, the syntax of which is as follows: datatype [ ] arrayName = new datatype [size];
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.
It can be done by specifying its type and size, initializing it or both.
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) {};
};
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