You have a mismatch in types between reference and pointer, so the code shouldn't compile. Since you're checking for a null pointer, you apparently want to deal with pointers, so the code should be something on this general order:
class A{...}
class B: public A{...}
A& x;
if (dynamic_cast<B *>(&x))!=0)
// cast was successful
else
// cast wasn't successful
You could also use references throughout, but if you do then an unsuccessful cast is signaled by throwing a std::bad_cast
exception:
void f(A &a) {
try {
B &b = dynamic_cast<B &>(a);
b.do_something_specific_to_b();
}
catch (std::bad_cast const &b) {
// `a` wasn't of type `B`
}
}
Note, however, that dynamic_cast
is primarily useful in cases like this, where you're receiving the pointer/reference as a parameter, or for things like a collection of pointers, some of which may point to various different types:
std::vector<A *> objects;
for (auto const *a : objects) {
B *b = dynamic_cast<B *>(a);
if (b != nullptr)
b->do_B_specific_stuff();
else
a->do_generic_A_stuff();
}
Finally, I'd note that if you find yourself using dynamic_cast
very often, chances are pretty good that you're doing something wrong. I've used C++ since before dynamic_cast
existed, and in the time it has existed, the number of times I've had to use it could probably be counted on the fingers of one hand (with a couple left over). There are times and places where it's useful (and a few where it's really important), but they really are fairly unusual.