C + + RTTI

Source: Internet
Author: User

one, definition : Rtti:run Time type identification, runtime types recognition: Refers to a program can use a pointer or reference to a base class to retrieve the actual derived type of the object it refers to. usage : Two operators in C + + provide Rtti: (1)typeid operator : Returns the actual type of the object that the pointer or reference refers to. (2)dynamic_cast operator : A pointer or reference to a base class type safely Note : This two operator returns dynamic type information only for classes with one or more virtual functions----that is, executing the RTTI operator at run time For other types, the static type of information is returned---that is, the RTTI operator is evaluated at compile time. third, Detailed introduction :(1) typeid header file : # include<typeinfo> Syntax --Two forms: typeID (Type), typeid (expression ) is an arbitrary expression or type name. Common uses : to compare the types of two expressions, or to compare the type of an expression to a particular type. typeID return type :type_info&, defined as follows:
    classtype_info{ Public: Virtul~Type_info (); BOOL operator== (ConstTYPE_INFO&AMP;RHS)Const; BOOL operator!= (ConstTYPE_INFO&AMP;RHS)Const; BOOLBefore (ConstTYPE_INFO&AMP;RHS)Const; Const Char* Name ()Const; Private: Type_info (Consttype_info&RHS); Type_info&operator=(Consttype_info&RHS); } 

Interface Description : operator = = and operator! =: comparison operator, returns whether two types are (or are not) the same type (note: base class and derived class are not of the same type!) )。 Before: Returns True if the type precedes the RHS type in the type sort. Name: Returns the names of the types (the specific values used, depending on the specific compiler) (the string ending with a. Note : The default constructor and copy constructor of the Type_info class and the assignment operator are defined as private, so objects of type type_info cannot be defined or copied. The only way to create a Type_info object in a program is to use the typeid operator. Example :
#include <iostream>#include<typeinfo>using namespacestd; structBase {}; structDerived:base {}; structPoly_base {Virtual voidMember () {}}; structPoly_derived:poly_base {}; intMain () {intA; int*PA; cout<<"int is:"<< typeID (int). Name () <<Endl; cout<<"A is:"<< typeID (a). Name () <<Endl; cout<<"PA is:"<< typeID (PA). Name () <<Endl; cout<<"*pa is:"<< typeid (*PA). Name () << Endl <<Endl;        Derived Derived; Base* PBase = &derived; cout<<"Derived is:"<< typeid (derived). Name () <<Endl; cout<<"*pbase is:"<< typeid (*pbase). Name () <<Endl; cout<<"same type?"; cout<< (typeID (derived) ==typeid (*pbase)) << Endl <<Endl;        Poly_derived polyderived; Poly_base* Ppolybase = &polyderived; cout<<"polyderived is:"<< typeid (polyderived). Name () <<Endl; cout<<"*ppolybase is:"<< typeid (*ppolybase). Name () <<Endl; cout<<"same type?"; cout<< (typeID (polyderived) ==typeid (*ppolybase)) << Endl <<Endl; return 0; }  

Run Result:(tried two compilation environments: g++ (GCC) 4.4.6 20120305 (Red Hat 4.4.6-4)  and VC6.0)g++ results:

VC6.0 results:

Note: Although typeID (*ppolybase) returns a derived class type, typeID (ppolybase) still returns the base class pointer type. Similarly, the reference is similar: if R is a reference, typeID (R) returns the derived class type, typeID (&R) still returns the base class type.
Note: The results of the two compilation environments are different---that is, the results returned by typeID in various compilation environments are inconsistent! Why is that? because: Standard C + + stipulates that the exact definition of the Type_info class varies with the compiler, as long as all implementations provide the above basic operations (see class definition). That is, the specific implementation details, the compiler vendor can decide. Note: When running the VC6.0, remember to add the compile option to "/gr", otherwise the warning (Project-Setup--c/c++---project option) will appear at compile time. Because VC6.0 does not turn on Rtti by default. (2) Dynamic_cast syntax form:dynamic_cast<t> (v), converts the object V to an object of type T. Premise: v Either is a base class pointer to its derived class object, or a base class object that references its derived class object. Otherwise, V returns null (when the pointer is) or throws Std::bad_cast (defined in header file <typeinfo>) exception (for reference type), and T is the expected derived class pointer type or derived class reference type. Also, the base class that the V points to must contain a virtual function, that is, a polymorphic type, or a compilation error. Common wording: I, poly_derived* derivedptr = dynamic_cast<poly_derived*> (ppolybase);//Convert to a pointer to poly_derived type, failed to return null ; II, poly_derived& derivedref = dynamic_cast<poly_derived&> (polyderived); Converts to a poly_derived reference and throws a Bad_cast exception if it fails. See examples:
#include <iostream>#include<typeinfo>using namespacestd; structPoly_base {Virtual voidMember () {}}; structPoly_derived:poly_base {}; intMain () {poly_derived polyderived; Poly_base* Ppolybase = &polyderived; Poly_base& rpolybase =polyderived; if(poly_derived* derivedptr = dynamic_cast<poly_derived*> (ppolybase))//Base Pointer{cout<<"dynamic_cast pointer success."<<Endl; }        Else{cout<<"dynamic_cast Pointer fail!"<<Endl; }        Try{            Constpoly_derived& Derivedref = dynamic_cast<ConstPoly_derived&>(rpolybase); cout<<"dynamic_cast reference success."<<Endl; }Catch(bad_cast) {cout<<"dynamic_cast reference fail."<<Endl; } cout<<"same type?"; cout<< (typeID (rpolybase) ==typeid (*ppolybase)) <<Endl; return 0; }  

Running results: Reference article:

1. http://www.cplusplus.com/reference/typeinfo/type_info/

2. Http://en.cppreference.com/w/cpp/language/typeid3.  Http://stackoverflow.com/questions/1986418/typeid-and-typeof-in-c4. http://renhl252.blog.163.com/blog/static/2122100720098229281284/reprinted from: http://blog.csdn.net/heyabo/article/details/8348624

C + + RTTI

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.