Search code examples
classvariable-length-array

Declaring variable length array in a class


folks. Here's my piece of code:

class Solar_system
{
    public:

    Solar_system()
    {
        planet_no = 5;
    }

    int planet_no;
    int planet[planet_no];
};

Error given: invalid use of non-static data member Solar_system::planet_no

Any help would be greatly appreciated.


Solution

  • I am assuming this is in C++.

    When creating an array at run time it should be dynamically allocated. Like this:

    http://www.cplusplus.com/doc/tutorial/dynamic/

    So you would create a pointer in the class and then set the array up:

    int * planet;
    int planet_no;
    Solar_system()
    {
        planet_no = 5;
        planet = new int[planet_no];
    }