Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);
like image 374
Dog Avatar asked Aug 15 '26 19:08

Dog


1 Answers

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.

like image 115
imreal Avatar answered Aug 17 '26 09:08

imreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!