Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

dynamic cast - C++ dynamic_cast - polymorphic requirement and downcasting

In the following code, while constructing obj in case 1, we construct a derived class object too, but its member functions are just inaccessible to obj. So while downcasting (i.e., in case 2), using obj as source, we have the constructed derived in it already. Why would obj need to be polymorphic?

If I confused you with my above description, why doesn't obj need to be polymorphic when upcasting, but while downcasting it does need to be polymorphic while using dynamic_cast?

class base
{
public:
    base()
    {
        cout<< " 
 base constructor 
";
    }
};

class derived : public base
{
public:
    derived()
    {
        cout << " 
 derived constructor 
";
    }
};

base *obj = dynamic_cast<base*> (new derived); // case 1: explicitly upcasting
derived *OBJ = dynamic_cast<derived*> (obj);   // case 2: error
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

In order for dynamic_cast to work the object needs to be polymorphic. The reason for this is that dynamic_cast needs somewhere to store the type information that is will use to perform the cast, and it does this by storing the information alongside the vtable for the class. In order for there to be a vtable you need to make at least one of your methods virtual.

The easiest way around this is to flag the base class destructor as virtual.

Upcasting (ie derived to base) doesn't needs a cast as the compiler is able to check that the cast would work at compile time. However, the same isn't true when downcasting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...