I'm trying to understand how arrays work in C++. Some good threads on SO, but one question I have that I can't find the answer to is:
Why is it possible to declare array data members with no size? I thought in C++ an array size had to be a compile-time constant?
Example:
#include<iostream>
class Object{
public:
Object(std::size_t n){
for(std::size_t i = 0; i<n; ++i) { array[i] ='X'; }
//prints 0 because 'sizeof' is compile-time operator
std::cout << "compile-time size: " << sizeof(array) << std::endl;
std::cout << "run-time size " << n << std::endl;
}
private:
char array[];
};
int main( int argc, char** argv )
{
Object obj(10); //10 chars
std::size_t n;
std::cin >> n;
Object obj2(n); //n chars in automatic storage i.e. on the stack??
}
Input:
n = 1000
Output:
compile-time size: 0
run-time size 10
compile-time size: 0
run-time size 1000
Does this mean that obj2's array data member is stored in automatic storage, but the size is determined dynamically at runtime ?
Thanks