This is the code:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class A {
public:
virtual const string f() const { return "A"; }
};
class B : public A {
public:
const string f() const { return "B"; }
};
int main(int ac, char** av) {
vector<A> v;
v.push_back(B());
cout << v.at(0).f() << endl;
return 0;
}
Expected result is B
, but it's A
. As I understand object slicing is taking place. How to avoid it? Shall I store pointers in vector
instead of object instances? Is this the only choice?