As exercise, I am trying a container similar to the object std::array
with a class and I am stuck with this error (using in VSCode).
The class uses a C-style array to store the values of the Array
object and the size of the C-style array is defined by the input n
. This is how I define the object:
class Array {
int n;
int values[n]; // I use the C-style array
int size{n}; // define size for member function
public:
Array() = default;
// : n(0), val(0) {} // not sure how to create an empty container
Array(int val, int n) : n(n) { // I pass an initial to fill the entire Array
for (auto &item: values)
item = val;
}
int get_size() const {
return size;
}
};
The line at int values[n];
is creating the error message. I am not sure how to pass the value n
as input: I pass it in the list initialisation at Array(int val, int n) : n(n) {...}
but I am not sure if I have to define n
here or somewhere else. The idea is to define an a variable using Array arr1(3, 4);
for example.
Also, I am not sure how to create a default constructor which would make an empty array when using Array arr2;
for example. Everything turns around on the correct n
definition.
Additional notes:
- later, I will implement more member functions like
get_size()
which also depends onn
- in this exercise, I am intentionally trying to avoid template classes (which is a possible solution)
- posts similar to this question, which however I couldn’t relate:
- member variable as default argument?
- initializing default parameter with class member function/variable