I have the following two classes, one inherits from the other
Class A{
void print(){cout << "A" << endl;}
}
Class B : A{
void print(){cout << "B" << endl;}
}
Class C : A{
void print(){cout << "C" << endl;}
}
Then in another class I have the following:
vector<A> things;
if (..)
things.push_back(C());
else if (..)
things.push_back(B());
things[0].print();
this always prints A
I’d like it to print B or C depending on which thing I’ve added to the vector
how do I do this?
I’ve tried abstraction but I’m not entirely sure how to use it in C++ and it hasn’t been working for me
As mentioned, you need
virtualfunctions to enable polymorphic behaviour and can’t store classes directly by value in thevector.When you use a
std::vector<A>, you are storing by value and thus objects that you add, e.g. viapush_back()are copied to an instance of anA, which means you lose the derived part of the objects. This problem is known as object slicing.As already suggested you can avoid that by storing pointers (or smart pointers) to the base class, so only pointers are copied into the
vector: