I came across an old SO post about inheriting from std::vector. One of the comments made was unclear to me, why does slicing occur when you inherit from a standard library container and use a pointer/reference to the base?
#include <vector>
#include <iostream>
using namespace std;
class MyVec : public vector<int>
{};
void printTypeBase(vector<int>& vecObj)
{
cout << "base parameter ref: " << typeid(vecObj).name() << endl;
}
void printTypeDerived(MyVec& vecObj)
{
cout << "derived parameter ref: " << typeid(vecObj).name() << endl;
}
int main()
{
auto myVec = MyVec{};
printTypeBase(myVec);
printTypeDerived(myVec);
}
Outputs:
base parameter ref: St6vectorIiSaIiEE
derived parameter ref: 5MyVec
When I try to dynamic_cast inside printTypeBase
:
auto temp = dynamic_cast<MyVec&>(vecObj);
I get a clarifying error message:
error: 'std::vector<int, std::allocator >' is not polymorphic
In retrospect, my question should have been why is std::vector
not a polymorphic type?