I have a problem with setting the size of my array. In my code I have:
class Test {
public:
....//Functions
private:
string name[];
};
Test() {
//heres where i want to declare the size of the array
}
Is this possible?
I have a problem with setting the size of my array. In my code I have:
class Test {
public:
....//Functions
private:
string name[];
};
Test() {
//heres where i want to declare the size of the array
}
Is this possible?
You will need to dynamically allocate memory for the array using new
.
Declare the variable like this:
private:
string* name;
And in your constructor do this:
int size = ...
name = new string[size];
And free the memory in the destructor like this:
delete [] name;
No. But you could use a vector of strings instead:
private:
std::vector<std::string> name;
Then in your constructor:
Test()
: name(sizeOfTheArray)
{
}
The vector will be sized for the number of strings you specify. This means all memory for the strings will be allocated at once. You can change the size of the array as you wish, but there's nothing saying you have to. Thus, you get all the benefits of using a dynamically allocated array, and then some, without the drawbacks.