Search code examples
c++arraysdynamicpolymorphismdynamic-arrays

How to create a dynamic array of objects polymorphically?


How can I create a dynamic array of objects polymorphically, if I have an abstract class with derived classes, and without using STL data structure classes? (vectors, list, etc)

A static array of objects

TwoDimensionShape *shapes[2];       
shapes[0] = &Triangle("right", 8.0, 12.0);  
shapes[1] = &Rectangle(10);  

I know I can't do this because you cannot create objects of an abstract class:

cin >> x;
TwoDimensionShape *s = new TwoDimensionShape [x];

EDIT:

Thanks to Nick, this works:

  int x = 5;
  TwoDimensionShape **shapes = new (TwoDimensionShape*[x]);

Solution

  • You can create an array of pointers to that class:

    TwoDimensionShape **s = new TwoDimensionShape*[x];
    

    And then construct each object with it's specific type:

    s[0] = new Triangle("right", 8.0, 12.0);  
    s[1] = new Rectangle(10);
    

    Similar to what you had. Remember to delete when you don't need anymore.