I’m having trouble with virtual methods. When I call f it doesn’t work. Why?
#include <iostream>
struct A {
virtual void f() const { std::cout << "In A"; }
virtual ~A() {};
};
struct B : A {
void f() const { std::cout << "In B"; }
};
int main()
{
A* a = new A();
B* b = dynamic_cast<B*>(a);
(*b).f();
delete a;
}
It doesn’t print anything at all, and I don’t get any errors. What did I do wrong?
What is wrong is you did not check if retuned pointer is
NULL.dynamic_casttells you if the actual object pointed byais of the typeb, which it is obviously not. And in such a scenario it will return you aNULL.Basically, You are dereferencing a
NULLpointer, causing an Undefined Behavior which unluckily for you doesn’t crash.When you use a language provided feature it should be used in the way mandated by the standard. The use of
dynamic_castwarrants aNULLcheck of the returned pointer.Your pointer
ashould actually point to an derived class objectb. You need:Also, your code must check the returned pointer: