Reputation:
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
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
Reputation: 71
Since it is not allowed, you can do one of these two things:
Upvotes: 0