user11313931
user11313931

Reputation:

How to declare an array without specifying its size, but with an initializer inside a class in C++?

It is allowed to declare an array without explicitly stating its size, if it has an initializer:

// very fine: decltype(nums) is deduced to be int[3]
int nums[] = { 5, 4, 3 }; 

However the same doesn't work when the array is declared in a class:

class dummy_class
{
    // incomplete type is not allowed (VS 2019 c++17)
    int nums[] = { 5, 4, 3 }; 
};

Why is this the case?

Upvotes: 10

Views: 1343

Answers (2)

songyuanyao
songyuanyao

Reputation: 172884

This is not allowed because non-static data members might be initialized in different ways (with different sizes), including member initializer list, default member initializer, aggregate initialization, ... But the size of array must be fixed and known at compile-time, which can't be postponed until the initialization. e.g.

class dummy_class
{
    int nums[] = { 5, 4, 3 }; 
    dummy_class(...some_parameters) : nums { 5, 4, 3, 2 } ()
    dummy_class(...some_other_parameters) : nums { 5, 4, 3, 2, 1 } ()
};

Upvotes: 14

Shiv Kumar
Shiv Kumar

Reputation: 71

Since it is not allowed, you can do one of these two things:

  • Either use the constructors/methods for initialization along with vector type declaration.
  • Or try making the variable static, but I am afraid that may not be helpful in your case.

Upvotes: 0

Related Questions