Lets say i have:
class Base {...};
class Derived1 : public Base {...};
class Derived2 : public Base {...};
class Derived3 : public Base {...};
class Store {
public:
void Add(const Base&); //Adds mix of Derived1/2/3
private:
vector<const Base*> vec;
vector<shared_ptr<const Base> > vec_smart;
};
//------------------------------------------------------
void Store::Add(const Base& b){
vec.push_back(&b); //got sliced
}
When using vector of pointers to Base, it got sliced. I suppose i have to use smart pointers but I cant get it to work.
I tried something like:
auto tmp = make_shared<const Base> (b);
vec_smart.push_back(shared_ptr<const Base>(b));
But it still got sliced. What Iam doing wrong?
EDIT: I have << operator in Base class that calls virtual print in Derived classes.
ostream & operator <<(ostream & os, const Base & x) {
x.print(os);
return os;
}
void Base::print(ostream& os) const {
os << "Base";
}
void Derived1::print(ostream& os) const {
os << "Derived1";
}
When i call
cout << b;
In Store::Add it outputs fine but when I iterate over vector after it got stored all i get is "Base"
ostream & operator <<(ostream & os, const Store & x) {
for (auto it = x.vec.begin(); it != x.vec.end(); ++it) {
os << *(*it) << endl;
}
return os;
}
Is it a bad design?