Let's take a look at the four major conversions that others summarize
Static_cast, dynamic_cast, Const_cast, reinterpret_cast
http://www.jellythink.com/archives/205
To add to this,
1.dynamic_cast the parent class must contain a virtual function when making a downstream conversion (essentially, a virtual function table must be included)
There is no problem with the upstream conversion (whether it is a virtual function or not), whether it is a pointer or a reference, it will have this restriction
This feature is mentioned in the above link but only said that in the void* conversion requires a virtual function, not comprehensive;
See the code below
1 classParent {2 3 Public :4 voidfoo () {5 6cout <<"This is the Parent ' s foo function"<<Endl;7 }8 9 };Ten classChilda: PublicParent { One A - - }; the - classCHILDB: PublicParent { - - + - }; + Atypedefvoid(*fun) (void); at - intMainintargcChar**AGR) - { -Parent * pp =NewParent (); - -childa* PA = dynamic_cast<childa*>(PP); in
/*Parent pp;
parent& pRea = pp;
childa& pa = dynamic_cast<childa&> (PRea);
*/
To report the same mistake
- return 0; to}
Because there is no virtual function in the base class parent, the error is directly in line 28, and the compilation is not possible.
The error is: the operand of the run-time dynamic_cast must contain the Polymorphic class type;
2.dynamic_cast can reference the type of conversion, but for the downstream conversion, compile without error, run times wrong
See the following code, (contains the same base class, cross-class conversions)
1 //Test.cpp: Defines the entry point of the console application. 2 //3 4#include"stdafx.h"5#include <iostream>6 using namespacestd;7 classParent {8 9 Public :Ten Virtual voidfoo () { One Acout <<"This is the Parent ' s foo function"<<Endl; - } - the }; - - - classChilda: PublicParent { + - + A }; at - classCHILDB: PublicParent { - - - - }; in -typedefvoid(*fun) (void); to + intMainintargcChar**AGR) - { the Parent pp; *parent& PRea =pp; $childa& PA = dynamic_cast<childa&>(PRea);Panax Notoginseng /* - Childb pp; the childb& pRea = pp; + childa& pa = dynamic_cast<childa&> (pRea); A */ the + - $ $ return 0; -}
Error is: Std::bad_cast, run times wrong
But the cross-class conversions for the same base class
The pointer is not an error, just get the empty
//Test.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>using namespacestd;classParent { Public : Virtual voidfoo () {cout<<"This is the Parent ' s foo function"<<Endl; }};classChilda: PublicParent {};classCHILDB: PublicParent {};typedefvoid(*fun) (void);intMainintargcChar**AGR) {Childb* pp =NewChildb; Childa* PA = dynamic_cast<childa*>(PP); ///the PA here is null, but not an error . return 0;}
dynamic_cast C + +