Is there something inherently wrong with dynamic downcasting in C ++?

I've heard him say several times that if you need to dynamically downgrade, there might be something wrong with the design. I see it as a similar mechanism for COMs queryinterface, querying an object at runtime to see what interfaces it supports, and then referring appropriately (and) to the appropriate method.

Is there anything wrong with that?


source to share

2 answers

There is nothing wrong with this, and sometimes it is appropriate, but it is often bad design for writing code that makes decisions based on the dynamic type of an object. If you have something like this:

void foo(Base const *base) {
  Derived1 const *derived1 = dynamic_cast<Derived1 const *>(base);
  if (derived1) {
    // Do stuff

  Derived2 const *derived2 = dynamic_cast<Derived2 const *>(base);
  if (derived2) {
    // Do stuff


you would probably be better off putting this functionality in derived classes as a virtual function and letting the language's built-in dynamic dispatch take care of which code to run. This way, if you add Derived3

later, you don't need to find all the places in your code where you check for Derived

or Derived2

, and add check for Derived3

. Just implement the virtual function in Derived3

and all existing virtual function calls will work.



As with many other programming language features, there are corresponding uses (for example, COM might be one such case), but in most cases this indicates that you have created a type hierarchy that is not rich enough for your needs (does not offer all the operations you need) or that you are forcing an inheritance relationship on types that are not actually related (and therefore have different sets of operations).

Note that this also applies to the COM interface, where, apart from basic publishing, interfaces are supported, objects are crawled very little. But in this particular case, the binding of unrelated types in the hierarchy is a necessity for a specific interface defined in the system.



All Articles