An object child
derived from base
class base
{
public:
virtual int get() const { return 0;}
~virtual base(){}
};
class child : public base
{
public:
virtual int get() const override { return 1; }
};
is sliced when added to a container e.g.
std::vector<base> bases;
bases.push_back(child());
and the code below returns 0
bases.at(0).get();
Even if the signature of push_back is:
void push_back( const T& value );
void push_back( T && value );
which shouldn't incur the object to be sliced.
For example the code below results in bad_cast
dynamic_cast<child &>(bases.at(0))
Whereas calling with child of base exhibits polymorphic behaviour
void toto(base const & e)
{
std::cout << e.get() << std::endl;
}
which implies the object is not anymore a child; where did it get sliced? what does actually happen?
Would it be possible to setupbase
or child
such that is copes with being placed in the container and the object does not lose its polymorphic nature?
This is a rationale question, and it is already known that an object is copied, so please do not to suggest pointers/shared_ptr as this has been addressed elsewhere.