Dynamic array of abstract objects

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.

Any help will be appreciated.
How are the classes Element and Square defined?
here are .h files

1
2
3
4
5
6
7
8
9
10
class Element {
private:
    int duration;
protected:
    Element(int size);
    virtual int get_duration();
    virtual ~Element(void);
public:
    virtual void print() = 0;
};


1
2
3
4
5
6
class Square: public Element {
public:
    Square(int size);
    void print();
    virtual ~Square(void);
};
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?
yes it is an exercice where vectors are not allowed
i will test your code

edit: here is the error i have with the same line elements[index] = new Square(5);
1
2
3
main.cpp:17:24: error: expected type-specifier before ‘Square’
main.cpp:17:24: error: cannot convert ‘int*’ to ‘Element*’ in assignment
main.cpp:17:24: error: expected ‘;’ before ‘Square’
Last edited on
Is this error in your code or the code I posted? Are you sure you have not just a missing semicolon on the line above?
it's an exact copy and paste of your code
As you can see this runs without errors: http://ideone.com/7PJXH
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
Topic archived. No new replies allowed.