c++ – Why is dynamic_cast needed?

Question:

class A;
class B : public A;

B* b;
A* a = dynamic_cast<A*>(b);  // 1
A* a = (A*)b;  // 2

What is dynamic_cast ? What are the advantages of recording 1 over recording 2 and what are the disadvantages? When should you use which option?

Answer:

Actually, in the version as you wrote, you do not need to cast anything, because the object of the derived class is already an object of the base class. So you can just write

A * a = b;

But if the opposite is true –

B * b = a;

problems begin. Because it usually means bad design . You want to use the descendant exactly where only the ancestor is used. Those. in fact, add some cunning behavior where nothing is known about it and should not be known.

dynamic_cast keeps your entire program from crashing just because you did something wrong. Well, for example,

void func(Base*b)
{
    ((Derived*)b)->derivedfunc();
}

Here you are calling a member function that Derived but which Base does not. But what if you actually pass a pointer to Base into the function? Pointer to another child of Base who doesn't know anything about this function?

And dynamic_cast allows you to at least make sure that exactly what you want is happening, i.e. that there really is a pointer to Derived .

As for the C-style cast – (A*)b – perhaps the closest thing to reinterpret_cast is to just treat the bits as being of a different type. Without any checks. Which is already dangerous, but at least in the text of the program this long word – reinterpret_cast – will catch the eye as a pointer to the danger. And this is not a joke, I repeat Stroustrup – about long awkward titles ..._cast .

PS I don't need to remind you that virtual functions are required when using dynamic_cast , and explain why?

Scroll to Top