user1553248
user1553248

Reputation: 1204

Array declaration and size initialization (C++)

I'm not exactly sure how to pose this question so I'll start with some example code:

//header file
class A
{
public:
    A();
private:
    int x;
    std::string arr[x];
}

//cpp file

class A
{
public:
    A()
    {
     /*code to get the value of x from a cmd call*/
    }
}

Is this code valid? More specifically, can I have my string array in my header file be of size x, even though x is not specifically given a value until an A object has been created?

If this doesn't work, is my only other option to use a dynamically allocated array?

Upvotes: 1

Views: 979

Answers (5)

DrBards
DrBards

Reputation: 104

I found that on my mac, in x-code I could do the following

int x = foo() // get some value for x at runtime
int array[ x ];

but that is seriously uncool!! I just read yesterday that some compilers allow dynamic allocation on the stack, but I would recommend that you stay well clear of that.

If the value of x is not known until runtime, then you cannot allocate an array of size x until runtime. Think about what the compiler does: can an array of size x be allocated if we don't know how big x is? The only remaining option is to allocate at run-time (aka dynamically allocate).

Upvotes: 0

jxh
jxh

Reputation: 70382

The code is not valid. You should use a vector instead.

class A
{
public:
    A();
private:
    int x;
    std::vector<std::string> arr;
};

A::A () : x(command_gets_x()), arr(x) {}

Since arr is being initialized by the value of x, the constructor only works when x precedes arr in A (as it is in your definition). However, if the only purpose of x is to track the size of the array, it is not necessary, since a vector has the size() method.

class A
{
public:
    A() : arr(command_gets_x()) {}
    int x () const { return arr.size(); }
    //...
private:
    std::vector<std::string> arr;
};

Upvotes: 5

Matt Phillips
Matt Phillips

Reputation: 9691

No, you can't initialize arrays with non-const expressions. This will work, and is close to your original intent:

class A
{
   ...
   const int x = 3;
   std::string arr[x];
};

And in the .cpp file:

int A::x;

Upvotes: 1

bames53
bames53

Reputation: 88155

It's not valid. Array sizes must be constant expressions. Yes, you'll have to use dynamic allocation, though not necessarily directly. You can just use std::vector.

Upvotes: 3

Daniel Fischer
Daniel Fischer

Reputation: 183883

No, that's not possible, for one C++ doesn't have variable length arrays, and further, the array size must be a compile time constant.

You can in the constructor allocate an array with new, or, better use a std::vector.

Upvotes: 2

Related Questions