Polymorphism method issues

I have an abstract class called "Element" and in another class I have a variable
std::vector<Element> elements;
and a method
1
2
3
4
5
void MyClass::addElement(Element* element)
{
    elements.push_back(element);
    delete element;
}

this doesn't work. I just want this method to fill the vector with objects of subclasses of Element. How can I do this?
closed account (o1vk4iN6)
If you intend to use polymorphism you can't define the space required for it as it is unknown.

1
2
3
4
class A { int a; };
class B : public A { int b; };

std::vector<A> values = { B() }; // trying to store 8 bytes into 4 bytes 


In either case why are you calling delete on a variable passed through as a parameter, that is very sketchy. Whoever is passing an element through the addElement should be responsible for destruction.
Last edited on
To be consistent with the signature of your method MyClass::addElement, you need to declare your vector with Element pointer.

std::vector<Element*> elements;

And the delete on line 4 needs to go. If you delete the element after adding its pointer to the vector, then the pointer in the vector will be invalidated.

Andy
Last edited on
Topic archived. No new replies allowed.