Initialize array inside constructor

superFlaffo wrote:
Hi all, I need to initialize an array inside a constructor.

Can something like this be possible?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class ciao
{
public:
	// Constructor & Destructor
	ciao(int numValues);
	~ciao();

	double array[];
};

ciao::ciao(int numValues)
{
	anodes[numValues];
}

Thanks in advantage for the help!

The size of the array has to be fixed at compile time. If you want a dynamic size you could use std::vector instead.

http://www.cplusplus.com/reference/vector/vector/
Last edited on
You also could you a dynamic array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class ciao
{
public:
// Constructor & Destructor
ciao(int numValues);
~ciao();

double *array;

};

ciao::ciao(int numValues)
{
  array = new double[numValues]
}

ciao::~ciao()
{
  delete [] array;
}
You also could you a dynamic array.

Don't forget to save numValues somewhere in that class if you decide to use dynamic memory.
closed account (Nvq5oG1T)
Which are the advantages of saving numValues in the class, if a use a dynamic memory?
One advantage is that classes have a destructor which deletes the dynamic memory so you can't forget it.
Another advantage that it is accessible only inside the class - if you put it in the private or protected section - so no other code can accidentally modify it.
A big disadvantage of not saving the "size" in the class is that the class won't remember the size of the array. Since the class is the owner of this array it should know how big the array is in order to be able to help prevent buffer overrun problems.
Topic archived. No new replies allowed.