-2

I created an array with the length of x but I get the error

invalid use of non-static data member Test::x.

I tried to replace int newArray[x]; with int newArray = new int[x]; but still didn't work out. When I declared the newArray[x] in the constructor or put static const before int x = 10, the code run successfully. Why is that?

#include <iostream>
#include <vector>
using namespace std;

class Test
{
private:
    int x = 10;
    int newArray[x];
public:
    Test();
    ~Test();
};
int main()
{

    return 0;
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Minh Mốc
  • 101
  • 3

1 Answers1

1

int newArray[x]; won't work because size of a static array needs to be known at compile time. Adding static constexpr to the declaration of x makes it a compile time constant and that's why the code compiles.
int newArray = new int[x]; won't work either, because operator new returns a pointer, which cannot be assigned to an integer. Having said that, consider using std::vector instead.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93