I have a basic C++ question about inheritance and virtual methods.
Please regard this code:
#include <iostream>
#include <vector>
using namespace std;
class A {
public:
virtual void f() {cout << "A\n";};
};
class B : public A {
public:
void f() {cout << "B\n";};
};
int main() {
A a;
B b;
vector<A> v;
v.push_back(a);
v.push_back(b);
for (int i = 0; i < v.size(); ++i)
v.at(i).f();
}
If I execute this code, it prints out
A
A
I do not understand why it does not print
A
B
because the "f" method is declared as virtual. I would like to know why the program behaves in this way.
Thanks in advance