Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Built-in array with variable size?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading