Reputation: 3381
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?
Upvotes: 0
Views: 78
Reputation: 596352
A
does not derive from B
(the reverse is true). You are creating an instance of A
, not of B
. Using dynamic_cast
to cast an A
object into a B*
pointer will result in a null pointer, which you are not checking for before calling B::print()
. Calling a non-static class method via a null pointer is undefined behavior, see: What will happen when I call a member function on a NULL object pointer?
Upvotes: 2