A* a;
This just gives you a pointer to an A
. It doesn't point anywhere in particular. It doesn't point at an A
or B
object at all. Whether your code works or not depends on the dynamic type of the object it is pointing at.
So there are two situations you might want to know about. First, this one:
A* a = new A();
B* b = dynamic_cast<B*>(a);
b->SetVal(2);
This will give you undefined behaviour because the dynamic_cast
will return a null pointer. It returns a null pointer when the dynamic type of the object is really not a B
. In this case, the object is an A
. You then attempt to dereference the null pointer with b->SetVal(2)
, so you get undefined behaviour.
A* a = new B();
B* b = dynamic_cast<B*>(a);
b->SetVal(2);
This will work fine because the object really is a B
object. The dynamic cast will succeed and the SetVal
call will work just fine.
However, note that for this to work, A
must be a polymorphic type. For that to be true, it must have at least one virtual member function.