I have this snippet:
#include <iostream>
#include <vector>
class A {
public:
void m() {
std::cout << "hi";
}
};
class B : public A {
public:
void m() {
std::cout << "hello";
}
};
int main() {
std::vector<A*> v;
v.push_back(new A);
v.push_back(new B);
v.push_back(new A);
for (A *obj : v)
obj->m();
}
The problem is that this program prints hihihi
instead of hihellohi
, and it means that it always calls the m()
method of the static type (i.e. A
) rather than the dynamic one (B
). How can we always call the m()
method of the dynamic type?
Thank you for your help.