Dynamic_cast c++ type conversion

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Dynamic_cast is used only for object pointers and references, it ensures that a type conversion is a perfectly legitimate request object.

Therefore, dynamic_cast to one of its base class in the conversion of a class, always successful:

    class CBase{ };  
    class CDerived:public CBase{ };  
    CBase b; CBase* pb;  
    CDerived d; CDerived* pd;  
    pb = dynamic_cast<CBase*>(&d);    // ok:derived-to-base  
    pd = dynamic_cast<CDerived*>(&b); // wrong:base-to-derived  

This program fragment of second conversion will generate a compiler error, because in the dynamic_cast base class to inherit such conversion is not allowed, unless the base class is polymorphic.

The following example provided in the base class to add a virtual function, the base class supports polymorphism.:

class CBase
{
public:
	virtual void test(){};
};
class CDerived:public CBase
{
};

int main()
{
	CBase *b= new CDerived();
	CBase *pb;
	CDerived d;
	CDerived* pd;
	pb = dynamic_cast<CBase *>(&d);
	pd = dynamic_cast<CDerived *>(b);
}
Thus, PD = dynamic_cast<CDerived; *> (b) from a base class to class inheritance can be successful. This is the c+ + polymorphism Charm (more detailed understanding, please refer to teacher Hou Jie translation of "to explore the depth of C+ + object model", you will find all the answers)!


Look at the example of a multiple inheritance:

class Animal   {public: virtual ~Animal(){};   int m1; };
class Creature {public: virtual ~Creature(){}; int m2; };

class Bird:public Animal, public Creature { };


int main()
{
         Bird *bird = new Bird;
        Creature *creature = dynamic_cast<Creature *>(bird);//case 1
        Animal *animal = dynamic_cast<Animal *>(creature);//case 2

        Creature *creature1 = new Creature;
        Animal *animal1 = dynamic_cast<Animal *>(creature1);//Case 3 this is also normal execution, I very strange, who can tell me? 
}

The above code case1 conversion and Dan Jicheng, case 2 is due to the effect of case 1, can convert a, case 3 do not understand, please master pointing, continued to see "to explore the depth of C+ + object model .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Armstrong at December 15, 2013 - 3:44 AM