Hi
I'm trying to have a dynamic array of abstract objects.
The case is I have an abstract class Element, and two derivated class Circle and Square.
What I would like to do is store in an array both Circle and Square.
I know vector is the best option but this is not possible in this case.
This is what I've tried right now :
1 2 3 4 5 6 7 8 9
//constructor
this->elements = new Element *[size];
for (int i = 0; i < this->size; i++) {
this->elements[i] = 0;
}
//later
this->elements[index] = new Square(5);
//destructor
delete [] this->elements;
but this line : this->elements[index] = new Square(5); (same error with Circle)
returns me an error I don't understand : "cannot convert ‘int*’ to ‘Element*’ in assignment"
I guess this is related to pointers but I don't understand how.
That should not cause the error you are getting.
I tested with this code and that gives no compiler errors:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{
int size = 10;
int index = 0;
//constructor
Element** elements = new Element *[size];
for (int i = 0; i < size; i++) {
elements[i] = 0;
}
//later
elements[index] = new Square(5);
//destructor
delete [] elements;
}
I know vector is the best option but this is not possible in this case.
I doubt it's not possible. Or did you teacher tell you this?
I finally found the error thanks to you
the fact is that your code was working in a new project, so I understood that the error was that class Square was not imported ! (yes it's a super dummy error)
again thanks a lot