Alternative way to initialize arrays in the header file without C ++ 11

advertisements

I've made a class in my header file which creates and populates three arrays like so:

class ExampleClass {
private:
    string array1[5] = {"test1", "test2", "test3", "test4", "test5"};
    double array2[4] = {20.7, 26.4, 27.8, 31.1};
    double array3[4] = {19.1, 25.8, 27.3, 32.3};
};

When building I'm receiving a warning about this requiring -std=c++11 or -std=gnu++11 to work. It builds fine and works how I want for me, but is this something I should worry about in case I was going to include it in a uni project for example?

Is it a case where there's an older alternative that does the exact same, or was this only possible from C++11?


is this something I should worry about in case I was going to include it in a uni project for example?

If you're writing a project for an assignment you should pay attention to the requirements of the assignment. It should specify a platform, compiler, and build flags that your code must build and run on. If those requirements allow you to use C++11 then you're fine, if they don't then you'll have to find an alternative. And remember to always test your work on the platform, compiler, etc. that the graders will be using.

Is it a case where there's an older alternative that does the exact same, or was this only possible from C++11?

There is no pre-C++11 alternative that does exactly the same thing; prior to C++11 it was impossible to specify an initializer for member arrays. The closest you could get was to allow the default initialization to occur and then re-initialize the array in the constructor:

struct S {
    string array1[5];
    S() {
        string init_values[5] = {"test1", "test2", "test3", "test4", "test5"};
        for (int i=0; i<5; ++i) {
            array1[i] = init_values[i];
        }
    }
};

C++11 introduced uniform initialization:

struct S {
    string array1[5];
    S() : array1{"test1", "test2", "test3", "test4", "test5"}
    {}
};

And in-class initialization:

struct S {
    string array1[5] {"test1", "test2", "test3", "test4", "test5"};
};