I hope the title is not confusing. I am trying to understand the following issue that arises from defining methods of a class virtual or not in C++. Imagine I have a base class A and a derived class B, such that
class A {
public:
void print() { cout << "A"; }
}
class B : A {
public:
void print() { cout << "B"; }
}
If I know execute the code below, the print command would print out "A".
A *a = new A();
B *b = new B();
((A *)b)->print(); // this prints "A"
However, if I declare the "print" methods in both classes as virtual, I would instead see a "B" printed in my screen. Why is this happening exactly?
static_cast
, andreinterpret_cast
might work in practice but give UB.