3

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]);

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I have a problem, int x = 5; TwoDimensionShape **shapes = new (TwoDimensionShape *)[x]; The compiler says "A value of type TwoDimensionShape * cannot be used to initialize an entity of type TwoDimensionShape **
You are missing an asterisk on shapes and one afer TwoDimensionShape: TwoDimensionShape **shapes = new (TwoDimensionShape*)[x];
Huh, that's weird, when I clicked to edit and it was in there, but nonetheless it still gives an error
Can you update the question on the top to see how the code is after this change?
i figured it out, the [x] is supposed to be inside the parrentheses after the *, I will post an update
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.