0

i want to use values ​​that I declare in the constructor with passed variables in the Header file. Is that somehow possible? In my case I give the constructor two int values ​​with these values ​​I want to set the size of a array. Was there a way to do that in the header file? Like this:

class test
{
public:
    test(int valueA);  //Constructor
 float testArray [valueA];  //Array
}
MB1995
  • 29
  • 3

2 Answers2

3

No you can't do it like this and no, that's not even legal C++. The size of an array must be known at compile time. You should use std::vector<float> instead and initialize it in the constructors initializer list:

#include <vector>

class test
{
public:
    test(int valueA) : testArray(valueA) {}
    std::vector<float> testArray; 
}

This will initialize testArray with valueA values.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30
  • is that also possible for 2-D Vectors? – MB1995 Mar 17 '20 at 13:08
  • @MB1995 Yes, there are many question that cover this topic. [This one](https://stackoverflow.com/questions/17663186/initializing-a-two-dimensional-stdvector) for example. – Lukas-T Mar 17 '20 at 14:09
0

As written: no.

Two options:

Use a class that doesn't need it's size set (like std::vector). This is the better approach.

Or dynamically create the array once you do know the size. This isn't a great approach, but may be closer to the intent of the original question. As pointed out in the comments to avoid dynamic memory issues, since there is a destructor you probably want a copy constructor and a copy assignment constructor to ensure you don't end up with two text classes sharing the same array.

class test
{
public:
    test(int valA)
    {
        testArray = new float[valA];
    }

    ~test()
    {
        delete[] testArray;
    }
private:
    float* testArray
};
John3136
  • 28,809
  • 4
  • 51
  • 69