How can I declare an array without specific size as a class member? I want to set the size of this array immediately in the class constructor. Is it possible to do such thing without using the heap or without resizing the array?
-
In C++ the size of the array should be fixed during declaration of the array i.e. you have to use a constant size. For variable size you have to use the new operator or malloc but this creates array on the heap. – Bourne Jun 23 '13 at 08:55
-
In C++14, we'll have an option to use [`dynarray`](http://en.cppreference.com/w/cpp/container/dynarray/dynarray). For now, as others have said, `std::vector` is the way to go. – jrok Jun 23 '13 at 08:59
-
2Possible duplicate of [c++ declare an array of arrays without know the size](https://stackoverflow.com/questions/12830197/c-declare-an-array-of-arrays-without-know-the-size) – Damjan Pavlica Apr 27 '18 at 21:22
4 Answers
Variable length arrays are not allowed by C++ standard. The options you have are:
- Use a
std::vector
or - Use a pointer to dynamic memory
Note that Variable length arrays are supported by most compilers as a extension, So if you are not worried of portability and your compiler supports it, You can use it. ofcourse it has its own share of problems but its a option given the constraints you cited.

- 202,538
- 53
- 430
- 533
C++ requires the size of an automatic storage array to be known at compile time, otherwise the array must be dynamically allocated. So you would need dynamic allocation at some level, but you don't have to concern yourself with doing it directly: just use an std::vector
:
#include <vector>
class Foo
{
public:
Foo() : v_(5) {}
private:
std::vector<int> v_;
};
Here, v_
is a vector holding ints
, and is constructed to have size 5
. The vector takes care of dynamic allocation for you.
In C++14, you will have the option of using std::dynarray
, which is very much like an std::vector
, except that its size is fixed at construction. This has a closer match to the plain dynamically allocated array functionality.

- 223,364
- 34
- 402
- 480
You can use a vector, by including header file #include<vector>
It can grow and shrink in size as required and vectors have built in methods/functions which can make your work easy.

- 129
- 1
- 1
- 9
Class member array have to be declared with exact compile-time size. There's no way around it.
The only way you can declare an array as an immediate member of the class and yet be able to decide its size at run time would be the popular "struct hack" technique inherited from C.
Other than that, you have to declare your array as an indirect member of the class: either declare a member of pointer type and allocate memory later, or use some library implementation of run-time sized array (like std::vector
)

- 1
- 1

- 312,472
- 42
- 525
- 765