I am storing an objects with common parent in stl container (actually stack), but calling a virtual function on object inside of it results in calling an implementation in this common parent. See demo code:
#include <iostream>
#include <stack>
using namespace std;
class Z
{
public:
virtual void echo()
{
cout << "this is Z\n";
}
int x;
};
class A: public Z
{
public:
virtual void echo()
{
cout << "this is A\n";
}
};
int main()
{
A a;
a.x = 0;
Z z;
z.x = 100;
stack<Z> st;
st.push(a);
st.top().echo(); // prints "This is Z"
cout << "x = " << st.top().x << endl; // prints 0
st.push(z);
st.top().echo(); // prints "This is Z"
cout << "x = " << st.top().x << endl; // prints 100
return 0;
}