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.
This is called slicing. A a = B(); creates a copy which is of type A. All information about its source being B is forgotten. The only way to exploit polymorphism is through references or pointers (or mechanisms that allow compile-time polymorphism, like templates or function overloading for example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With