Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I can't provide an in-class initializer for std::vector data member

I’m trying to initialize the member vec within the class scope, but the compiler throws a more cryptic error.

class A {
public:
    static const size_t sz = 10;
    static const std::vector<double> vec{ sz }; // error
};

The compiler (gcc) gives the following error(s):

error: in-class initialization of static data member 'std::vector<double> A::vec' of non-literal type
   10 |     static std::vector<double> vec{ sz };
      |                                ^~~
error: non-constant in-class initialization invalid for non-inline static member 'A::vec'
   10 |     static std::vector<double> vec{ sz };
      |                                        ^
note: (an out of class initialization is required)

How I can fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Ordinarily, static data members may not be initialized in the class body. However, we can provide in-class initializers for static members that are only of const-qualified integral type. If non-integral static members are used, and you need to provide an in-class initializer, the data member shall be constexpr literal type. In any case, the initializers must be constant expressions. If the type of the member is not literal type (hence constexpr can’t be used), the static member shall not have a default member initializer, instead, it can be defined outside the class.

So your error is just because std::vector<double> is of non-integral type. Also, you can’t declare vec as constexpr because std::vector<double> is not a literal type.

So to fix your above example, you can do this:

class A {
public:
    static const size_t sz = 10;
    static const std::vector<double> vec;
};

const std::vector<double> A::vec{ sz };

(Demo)

As pointed out in the commnets, note that, making vec const-qualified, you will lose some of the vector features. For example, you can’t modify any element after adding it!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading