Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c++ - What is the proper use case for dynamic_cast?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...