0

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:

  • `int values[n]` is not valid in C++ – ChrisMM Apr 08 '22 at 14:38
  • 1
    You can't have array with variable length in class. How would compiler know what is the `sizeof` of this class? – Yksisarvinen Apr 08 '22 at 14:41
  • 2
    This is not similar to `std::array` at all - `std::array` is a template, and, in particular, the size is a template parameter and hence known at compile time. – Paul Sanders Apr 08 '22 at 14:42
  • 1
    Thank you Now I understand why I should use a template class instead. The compiler will know about `n` only if I create the blueprint for it: in this case decorating the class with `template`. In that case `int value[n]` will be valid. Then, declaring the Array in my original question should be changed to `Array<4> arr1(3);`. – Domenico Spidy Tamburro Apr 08 '22 at 15:25
  • 1
    That sounds better, yes. Might as well template the type of the array elements while you're at it. – Paul Sanders Apr 08 '22 at 15:25

0 Answers0