1

Chapter 2.3.2 of The C++ Programming Language lists this constructor:

class Vector {
public:
    Vector(int s) :elem{new double[s]}, sz{s} { }
private:
    double* elem;
    int sz;
};

As far as I know, the array size must be a constant expression, and s isn't. Is this legal? If so, why?

3
  • "the array size must be a constant expression" Since when? Commented Feb 20, 2022 at 19:33
  • You can dynamically allocate an array of a size which is not a constant expression. This is the reason why new[] was invented in the first place. A *declared * array size must be a constant, but new is not a declaration. Commented Feb 20, 2022 at 19:35
  • The size specified in a new expression is not required to be a constant expression. Also, in your code, elem is a pointer, not an array. Commented Feb 20, 2022 at 22:09

1 Answer 1

2

Yes, it's legal because the array is allocated at runtime with the 'new' operator.

If you want to allocate an array at compile-time, you must provide a const int, or constant expression.

int count = 0;
cin >> count; 
int* a = new int[count];  // This is dynamic allocation happen at runtime.
int b[6];                 // This is static allocation and it happen at compile-time.
Sign up to request clarification or add additional context in comments.

1 Comment

At block scope int b[6]; is not static allocation. It would be automatic storage duration, "allocated" when the scope is entered, not at compile-time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.