Let parent class A
and a child class B
be
// A.h
#include <iostream>
struct A {
virtual void print() {
std::cout << "A" << std::endl;
}
};
and
#include <iostream>
#include "A.h"
struct B : public A {
void print() override {
std::cout << "B" << std::endl;
}
};
Then in a program the following is possible:
int main() {
A a1;
a1.print(); // <-- "A"
B b1;
b1.print(); // <-- "B"
A* a2 = new B();
a2->print(); // <-- "B"
}
However, the following crashes:
B* b2 = dynamic_cast<B*>(new A());
b2->print(); // <-- Crashes
What is wrong here?