Below is the perhaps most simple example of a virtual function in C++:
#include <iostream>
class A {
public:
virtual void f() {
std::cout << "A";
}
};
class B : public A {
public:
void f() {
std::cout << "B";
}
};
int main() {
{
// calls f() in derived class
A* a = new B();
a->f();
}
{
// calls f() in base class
A a = B();
a.f();
}
}
The output of this program is BA
. I expected it to be BB
, i.e. call the base class in any case.
Why does using a base class pointer make a difference here?
I didn't find the explanation in the standard.