0

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.

nalply
  • 26,770
  • 15
  • 78
  • 101

2 Answers2

0

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];
}
jneff
  • 43
  • 4
  • Can you please tell me if the array should afterwards be deleted, and if so when. – Andrei Albu Jan 29 '13 at 21:16
  • Yes, it should be deleted. The class destructor is a good place to delete it. ~Solar_system(){ delete [] planet;} That way it is always called. If you need to resize/recreate the array you would delete it before setting it to a new block of memory as well. – jneff Jan 29 '13 at 22:57
0

Instead of doing your own memory management, use a suitable container. For example, std::vector.

class Solar_system {
public:

    Solar_system()
    {
        planets_.resize(5);
    }

    std::vector<int> planets_;
};