What is the right thing to do? I know that if the container is of base class value type, then derived object stored is \'sliced\'. If container is of derived class type, the
The most obvious solution would be to use std::unique_ptr:
class IBase {};
class Derived : virtual public IBase {};
std::vector<std::unique_ptr<IBase>> v;
v.push_back(std::unique_ptr<IBase>(new Derived()));
You could use std::shared_ptr, but it's ownership semantics significantly change the program's behaviour, keeping the dynamically allocated objects alive alive until nobody holds references to them.
[http://www.boost.org/doc/libs/1_51_0/libs/ptr_container/doc/ptr_container.html](The Boost pointer container library) is made just for this.
There is example with std::vector and std::shared_ptr. I think that's what you want.
#include <iostream>
#include <memory>
#include <vector>
class Base {
public:
virtual void foo() {
std::cout << "base" << std::endl;
}
};
class Derived : public Base {
void foo() {
std::cout << "derived" << std::endl;
}
};
int main()
{
std::vector<std::shared_ptr<Base> > v;
v.push_back(std::shared_ptr<Base>(new Base));
v.push_back(std::shared_ptr<Base>(new Derived));
for (auto it : v) {
it->foo();
}
}
If you want polymorphic behavior (and you do want it), then you must use pointers or references. That is well documented in many places.
And since you cannot use containers of references, you have to use containers of pointers.
Now, you can use any type of pointer you see fit: unique_ptr
, shared_ptr
or raw pointers.