Let’s say I have a class Foo. The class should store an array of Foo. I thought this would work:
class Foo
{
private:
Foo *myArray[];
//...
public:
Foo()
}
Foo::Foo()
{
myArray = new Foo [10];
}
But it doesn’t. Any suggestions on what I am missing?
There are two problems with this code. First, your array declaration syntax is incorrect and throws an error during compilation. You should declare the array pointer like this:
Secondly, if you attempt to instantiate a Foo object, you will create an infinite loop. This is because the new keyword will call the default constructor of the objects it’s creating. For every Foo you instantiate, 10 more will be instantiated in the constructor, which will in turn each create 10 more Foo objects. You can solve this by having a separate method in your class which instantiates the array and which is hopefully not always called on every Foo object.