In the world of C + + There are two concepts, the upward type conversion, the downward type conversion, respectively describing the subclass to the base class, and the base class to the subclass of the coercion type conversion.
Force type conversions Up
Cutting: Overlay methods and sub-data loss phenomena generation cut (slice)
[CPP]View PlainCopy
- Class Base
- {
- Public
- int b;
- virtual void Test ()
- {
- cout << "base" <<endl;
- }
- };
- Class Derived: PublicBase
- {
- Public
- int D;
- virtual void Test ()
- {
- cout << "derived" <<endl;
- }
- };
- int main ()
- {
- Derived D;
- Base B = D; //Direct Assignment (generation of cutting)
- B.test ();
- base& B2 = D; //Use reference assignment (does not produce a cut)
- B2. Test ();
- base* B3 = &d; //Use pointer Assignment (does not produce cutting)
- B3->test ();
- return 1;
- }
Therefore, we conclude that the use of pointers and references in the upward casting process does not result in cutting, whereas the use of direct assignment results in cutting.
Forcing type conversions down
Use dynamic_cast to force type conversions down. There are a few conditions for using this keyword
1. There must be a virtual function
2. The compiler's RTTI switch must be turned on (vc6:progect-> settings-C + + TAB->category[c++ language]-> Enable RTTI)
3. Must have an inheritance relationship
[CPP]View PlainCopy
- Base *b = new Derived;
- Derived *d = dynamic_cast<derived*> (b);
- if (!d)
- {
- cout << "Dynamic cast err!" <<endl;
- }
- Else
- {
- D->test ();
- }
In this example, the conversion succeeds if the above conditions are met. Otherwise, the Std::bad_cast exception is thrown, and the conversion returns null
Therefore, we can use dynamic_cast to determine whether there is an inheritance relationship for two classes
Up-type conversions and down-type conversions in C + +