0

I am unsure how to create an array of objects within its own class. For example:

class A { 
public:
  const static int MAX_SIZE = 10;

 private:
  A arrayOfOBjects[MAX_SIZE];


}

I get an error saying, "incomplete type is now allowed" How would I go about this? If I declare an array of objects from another class inside Class A it will work.. But how do I create an array of objects within its own class?

Emmett
  • 357
  • 2
  • 4
  • 15
  • 1
    A class cannot contains members of its own type. You would need to hold an array of smart pointers to `A`. – juanchopanza May 26 '13 at 09:02
  • Look at this: http://stackoverflow.com/q/16756876/2040040 – johnchen902 May 26 '13 at 09:02
  • @juanchopanza What about `std::array`? – Peter Wood May 26 '13 at 09:15
  • @PeterWood that shouldn't work either. But `std::vector` could. – juanchopanza May 26 '13 at 09:16
  • @juanchopanza Ah, it's an incomplete type. Yes, `vector` would work. – Peter Wood May 26 '13 at 09:19
  • @PeterWood correct. `std::array` poses the same problems as a standard fixed size C array, which is the same problem as having a single data member of type `A` within `A`. `std::vector` does not have that problem, because it allocates `A` objects dynamically and does not need to have the complete `A` type (although I am sure this hasn't worked in older compilers I have used). – juanchopanza May 26 '13 at 09:22
  • @juanchopanza Yes, some compilers it didn't work, also for the key/value pair of a `map`. I always thought it was a leaky implementation detail though. Why can't `array` be implemented like `vector`? – Peter Wood May 26 '13 at 09:26
  • 1
    @PeterWood because `std::array` is a no-overhead drop-in replacement for a fixed size C array, so all the data it holds is its elements. It cannot have a pointer that points to some dynamically allocated memory. – juanchopanza May 26 '13 at 09:32

3 Answers3

0

use a pointer. or shared_ptr etc and dynamically allocate the objects

class A { 
public:
  const static int MAX_SIZE = 10;

 private:
  A * arrayOfOBjects[MAX_SIZE];


}
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
0

You obviously can't contain an instance of the object in itself. It would take infinite amount of storage ;-)

For the same reason you can't contain several. Maybe you meant the array to be a static member that doesn't add to the state of one instance?

Balog Pal
  • 16,195
  • 2
  • 23
  • 37
0

By using pointers you can solve this problem

class A { 
public:
  const static int MAX_SIZE = 10;
  void allocate(){
     arrayOfOBjects=new A[MAX_SIZE];
  }
 private:
  A *arrayOfOBjects;
};

You can use this as following

A a;
a.allocate();
apm
  • 525
  • 6
  • 19