Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have been told many times (and seen myself in practice) that the use of dynamic_cast often means bad design, because it can and should be replaced with virtual functions.

For example, consider the following code:

class Base{...};
class Derived:public Base{...};
...
Base* createSomeObject(); // Might create a Derived object
...
Base* obj = createSomeObject();
if(dynamic_cast<Derived*>(obj)){
 // do stuff in one way
}
else{
// do stuff in some other way
}

It can be easily seen that instead of writing dynamic casts we can just add a virtual function doStuff() to Base and re-implement it in Derived.

In that case, my question is, why do we have dynamic_cast in the language at all? Is there an example in which the use of dynamic_cast is justified?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
255 views
Welcome To Ask or Share your Answers For Others

1 Answer

The trouble with virtual functions is that all classes in the hierarchy must have an implementation or be abstract, and that's definitely not always the right thing to do. For example, what if Base is an interface, and in the if, you need to access the internal implementation details of Derived? That's certainly not doable in a virtual function. In addition, dynamic_cast is needed for both upcasting and downcasting in certain multiple inheritance situations. And there are limits as to what can be done in virtual functions- for example, templates. And finally, sometimes you need to store a Derived*, not just call a function on it.

Essentially, virtual functions only work in some cases, not all of them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...