Suppose I have a class ElementA that derives from Element and I want to
store all kinds of elements in this list. I suppose I have to store pointers
in the vector instead of the elements themselves?

When I loop through the vector and retrieving all elements (well, the
pointers) with the iterator, the program always comes back to the baseclass.
I declared the functions (and the destructor) as virtual, but it won't work.

Anything to look out for?

---

And how do you correctly delete elements from such a vector? Retrieve them,
delete them and then clear the vector?



--- stefkeB ---

Re: vector<element> vs. vector <element *> by anton

anton
Fri Feb 06 05:12:34 CST 2004

stefkeB wrote:
> Suppose I have a class ElementA that derives from Element and I want to
> store all kinds of elements in this list. I suppose I have to store pointers
> in the vector instead of the elements themselves?
>
> When I loop through the vector and retrieving all elements (well, the
> pointers) with the iterator, the program always comes back to the baseclass.
> I declared the functions (and the destructor) as virtual, but it won't work.
>
> Anything to look out for?
>
> ---
>
> And how do you correctly delete elements from such a vector? Retrieve them,
> delete them and then clear the vector?
>
>
>
> --- stefkeB ---
>
>

You should call virtual methods. Simple example:

class Base
{
public:
Base() {}
virtual ~Base() {}

virtual void someMethod() const {
std::cout << "Base::someMethod" << std::endl;
}
};

class Derived : public Base
{
public:
void someMethod() const {
std::cout << "Derived::someMethod" << std::endl;
}
};

vector<Base*> v;
v.push_back(new Base);
v.push_back(new Derived);

v[0]->someMethod(); // should print Base::someMethod
v[1]->someMethod(); // should print Derived::someMethod

hth,
anton.