What is the advantage of using dynamic_cast instead of conventional polymorphism?

barak manos

We can use Polymorphism (inheritance + virtual functions) in order to generalize different types under a common base-type, and then refer to different objects as if they were of the same type.

Using dynamic_cast appears to be the exact opposite approach, as in essence we are checking the specific type of an object before deciding what action we want to take.

Is there any known example for something that cannot be implemented with conventional polymorphism as easily as it is implemented with dynamic_cast?

Christian Hackl

Whenever you find yourself wanting a member function like "IsConcreteX" in a base class (edit: or, more precisely, a function like "ConcreteX *GetConcreteX"), you are basically implementing your own dynamic_cast. For example:

class Movie
{
    // ...
    virtual bool IsActionMovie() const = 0; 
};

class ActionMovie : public Movie
{
    // ...
    virtual bool IsActionMovie() const { return true; }
};

class ComedyMovie : public Movie
{
    // ...
    virtual bool IsActionMovie() const { return false; }
};


void f(Movie const &movie)
{
    if (movie.IsActionMovie())
    {
        // ...
    }
}

This may look cleaner than a dynamic_cast, but on closer inspection, you'll soon realise that you've not gained anything except for the fact that the "evil" dynamic_cast no longer appears in your code (provided you're not using an ancient compiler which doesn't implement dynamic_cast! :)). It's even worse - the "self-written dynamic cast" approach is verbose, error-prone and repetitve, while dynamic_cast will work just fine with no additional code whatsoever in the class definitions.

So the real question should be whether there are situations where it makes sense that a base class knows about a concrete derived class. The answer is: usually it doesn't, but you will doubtlessly encounter such situations.

Think, in very abstract terms, about a component of your software which transmits objects from one part (A) to another (B). Those objects are of type Class1 or Class2, with Class2 is-a Class1.

Class1
  ^
  |
  |
Class2


A - - - - - - - -> B
    (objects)

B, however, has some special handling only for Class2. B may be a completely different part of the system, written by different people, or legacy code. In this case, you want to reuse the A-to-B communication without any modification, and you may not be in a position to modify B, either. It may therefore make sense to explicitly ask whether you are dealing with Class1 or Class2 objects at the other end of the line.

void receiveDataInB(Class1 &object)
{
    normalHandlingForClass1AndAnySubclass(object);
    if (typeid(object) == typeid(Class2))
    {
        additionalSpecialHandlingForClass2(dynamic_cast<Class2 &>(object));
    }
}

Here is an alternative version which does not use typeid:

void receiveDataInB(Class1 &object)
{
    normalHandlingForClass1AndAnySubclass(object);
    Class2 *ptr = dynamic_cast<Class2 *>(&object);
    if (ptr != 0)
    {
        additionalSpecialHandlingForClass2(*ptr);
    }
}

This might be preferable if Class2 is not a leaf class (i.e. if there may be classes further deriving from it).

In the end, it often comes down to whether you are designing a whole system with all its parts from the beginning or have to modify or adapt parts of it at a later stage. But if you ever find yourself confronted with a problem like the one above, you may come to appreciate dynamic_cast as the right tool for the right job in the right situation.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

What's the advantage of using std::allocator instead of new in C++?

From Dev

What advantage is there in using the $timeout in AngularJS instead of window.setTimeout?

From Dev

What is the advantage of using Spring PropertySource?

From Dev

What is the advantage of using scala pattern matching instead of java switch case?

From Dev

using dynamic_cast with templates

From Dev

What is the advantage of using arrayWithCapacity

From Dev

Using Polymorphism instead of Switch

From Dev

What is the advantage of using ObjectSet

From Dev

dynamic_cast and polymorphism

From Dev

c++ polymorphism with dynamic_cast and typeid

From Dev

What is the advantage of using an Dynamic object over creating a class of that object?

From Dev

What is the advantage of using multiple scanners?

From Dev

What is the advantage of using Supplier in Java?

From Dev

What is advantage of using service wrapper in Spring boot instead of jar running?

From Dev

Downcasting using dynamic_cast returns null

From Dev

What is the meaning of `*dynamic_cast<T*>(...)`?

From Dev

What is the advantage of using CocoaPods?

From Dev

What is the advantage of using Spot Fleet Autoscaling instead of AutoScaling Groups with a Spot Price?

From Dev

What is the advantage of using Thymeleaf instead of JSP in Spring?

From Dev

What advantage is there in using the $timeout in AngularJS instead of window.setTimeout?

From Dev

What is the advantage of using a spanned archive?

From Dev

What is the advantage of using scala pattern matching instead of java switch case?

From Dev

What is advantage of using LESS variables

From Dev

c++ polymorphism with dynamic_cast and typeid

From Dev

What is the advantage of using composite primary key instead of single primary key in this context?

From Dev

What is the advantage of using a require statement instead of require_once?

From Dev

What is advantage of using service wrapper in Spring boot instead of jar running?

From Dev

Is there an advantage in using global variables instead of pointers?

From Dev

Downcasting using dynamic_cast returns null

Related Related

  1. 1

    What's the advantage of using std::allocator instead of new in C++?

  2. 2

    What advantage is there in using the $timeout in AngularJS instead of window.setTimeout?

  3. 3

    What is the advantage of using Spring PropertySource?

  4. 4

    What is the advantage of using scala pattern matching instead of java switch case?

  5. 5

    using dynamic_cast with templates

  6. 6

    What is the advantage of using arrayWithCapacity

  7. 7

    Using Polymorphism instead of Switch

  8. 8

    What is the advantage of using ObjectSet

  9. 9

    dynamic_cast and polymorphism

  10. 10

    c++ polymorphism with dynamic_cast and typeid

  11. 11

    What is the advantage of using an Dynamic object over creating a class of that object?

  12. 12

    What is the advantage of using multiple scanners?

  13. 13

    What is the advantage of using Supplier in Java?

  14. 14

    What is advantage of using service wrapper in Spring boot instead of jar running?

  15. 15

    Downcasting using dynamic_cast returns null

  16. 16

    What is the meaning of `*dynamic_cast<T*>(...)`?

  17. 17

    What is the advantage of using CocoaPods?

  18. 18

    What is the advantage of using Spot Fleet Autoscaling instead of AutoScaling Groups with a Spot Price?

  19. 19

    What is the advantage of using Thymeleaf instead of JSP in Spring?

  20. 20

    What advantage is there in using the $timeout in AngularJS instead of window.setTimeout?

  21. 21

    What is the advantage of using a spanned archive?

  22. 22

    What is the advantage of using scala pattern matching instead of java switch case?

  23. 23

    What is advantage of using LESS variables

  24. 24

    c++ polymorphism with dynamic_cast and typeid

  25. 25

    What is the advantage of using composite primary key instead of single primary key in this context?

  26. 26

    What is the advantage of using a require statement instead of require_once?

  27. 27

    What is advantage of using service wrapper in Spring boot instead of jar running?

  28. 28

    Is there an advantage in using global variables instead of pointers?

  29. 29

    Downcasting using dynamic_cast returns null

HotTag

Archive