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
287 views
in Technique[技术] by (71.8m points)

c++ - FAQ: Why does dynamic_cast only work if a class has at least 1 virtual method?

This does not compile in C++:

class A
{
};

class B : public A
{
};

...

A *a = new B();
B *b = dynamic_cast<B*>(a);
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Because dynamic_cast can only downcast polymorphic types, so sayeth the Standard.

You can make your class polymoprphic by adding a virtual destructor to the base class. In fact, you probably should anyway (See Footnote). Else if you try to delete a B object through an A pointer, you'll evoke Undefined Behavior.

class A
{
public:
  virtual ~A() {};
};

et voila!

Footnote

There are exceptions to the "rule" about needing a virtual destructor in polymorphic types.
One such exception is when using boost::shared_ptr as pointed out by Steve Jessop in the comments below. For more information about when you need a virtual destructor, read this Herb Sutter article.


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

...