Static_cast and dynamic_cast Conversions

Source: Internet
Author: User

Original article link

Yi CThere are two types of conversions in the language:

Implicit and explicit Conversions

Implicit conversion: values and operations are performed between different data types, and parameters are passed through function calls ...... Compiler complete

 
CharCh;
IntI = CH;

Display conversion: add (type) variable before the type to convert the variable. Explicitly add users

 
Char* Pc = (Char*) Pb;
Void* PS = (Void*) Pa;


II. C ++
Type conversion in

Using these two methods, most of the types in C can be converted smoothly.

As to whether the conversion can be performed or not, the compiler does not need to be controlled by the user.

C ++ inherits the implicit and explicit conversions in C. However, such conversions are not secure and strict,

In addition to the complexity of the C ++ object model, C ++ adds four display conversion keywords. (C ++ is a strong language)

(Static_cast,Dynamic_cast,Const_static,Reinterpret_cast)

 

1 static_cast

(1) For basic data type conversion (char, Int), And the conversion between pointers

  test_enum type = test_enum_1;  
char ;
int B = static_cast int ();
char C = static_cast char (B );
type = static_cast (B );
char * pA = NULL;
int * pb = ( int *) Pa;
// int * pb = static_cast (Pa ); // error
// Pa = static_cast (PB) // error
Char* Pc = (Char*) Pb;
//Char * Pc =Static_cast<Char *> (PB );//Error

Void* P =Static_cast<Void*> (PA );
PB =Static_cast<Int*> (P );
PC =Static_cast<Char*> (P );

 

(2) Class-level conversion of class and subclass member function pointers

 

ClassA
{

Public:
Void Set(){}
};

ClassB:PublicA
{
Public:
Void Set(){}
};

TypedefVoid(A: * ps_mfunc )();//Pointer to the member function of Class

Ps_mfunc func = & ::Set;
Func = static_cast <ps_mfunc> (& B ::Set);//The base class points to the member function pointer of the subclass and must be converted.

(3) Conversions between classes and subclass pointers or references in the class hierarchy

Uplink conversion: subclass pointer or reference conversion to base class representation-Secure

Downstream conversion: Converting base class pointer or reference to subclass representation-dangerous (no dynamic type check)

 ClassA 
{
};
ClassB:PublicA
{
};
ClassC:PublicA
{
};
ClassD
{
};

A obja;
B objb;
A * pobja =NewA ();
B * pobjb =NewB ();
C * pobjc =NewC ();
D * pobjd =NewD ();

Obja = static_cast <A &> (objb );//Conversion to base class reference
Obja = static_cast <A> (objb );
Objb = static_cast <B> (obja );//Error cannot be converted

Pobja = pobjb; //Right base class pointer pointing to subclass object
//Objb = obja;//The pointer of the error subclass refers to the base class object.
Pobja = static_cast <A *> (pobjb );//Right base class pointer pointing to subclass
Pobjb = static_cast <B *> (pobja ); //Forcibly convert the OK base class to the subclass
//Pobjc = static_cast <C *> (pobjb );//Error is inherited from the conversion between derived pointers of the unified class.
//Pobjd = static_cast <D *> (pobjc );//Error: conversions between two non-associations

 

2 dynamic_cast

(1Conversion between class pointer objects or references of inheritance relationships

 ClassA 
{
};
ClassB:PublicA
{
};
ClassC:PublicA
{
};
ClassD
{
};

A obja;
B objb;
A * pobja =NewA ();
B * pobjb =NewB ();
C * pobjc =NewC ();
D * pobjd =NewD ();
//Obja = dynamic_cast <A> (objb );//Error non-Reference

Obja = dynamic_cast <A &> (objb );
//Objb = dynamic_cast <B &> (obja );//Error A is not a polymorphism type and cannot be converted. If there is a virtual function, it can be converted.

Pobja = dynamic_cast <A *> (pobjb );
//Pobjb = dynamic_cast <B *> (pobja );//The inheritance relationship of error a cannot be converted because it is not a multi-state type.
//Pobjb = dynamic_cast <B *> (pobjc );//The error C sibling relationship is not a polymorphism type and cannot be converted.
//Pobjb = dynamic_cast <B *> (pobjd );//Error D is irrelevant. It is not a multi-state type and cannot be converted.

 

 

(2) Contains the conversion of object pointers between virtual functions.

ClassA
{
Public:
Virtual ~ A (){}
};
ClassB:PublicA
{
};
ClassC:PublicA
{
};
ClassD
{
Public:
Virtual ~ D (){}
};
 
Pobjb = dynamic_cast <B *> (pobja );//The parent class of the worning inheritance relationship has a virtual function polymorphism.
Pobjb = dynamic_cast <B *> (pobjd );//Worning is irrelevant. D is a convertible polymorphism.
//The preceding result is: pobjb = NULL. A runtime error occurs here.

That is to say, except that the base class Pointer Points to the subclass object, there can be no virtual functions, and other functions must have virtual functions for dynamic_cast conversion.

So why? Next proceed>

 

(3) Dynam_castSecurity of conversion

Dynamic_cast is a dynamic conversion. It is meaningful only when the base class pointer is converted to a subclass pointer.

(Subclass pointer conversion is inherently possible for base class pointers: The base class Pointer Points to the subclass object OK ).

However, the base class pointer is not valid for every time it is converted to a subclass pointer: only the base class pointer itself points to the object of a derived class,

It is valid to convert the base class pointer to the corresponding derived class pointer.On the surface, this situation cannot be determined. In this case, dynamic plays a role.

Case 1: Static_cast Conversion

ClassA
{
};
 
ClassB:PublicA
{
Public:
IntM;//Member B
};

A * pobja =NewA ();
B * pobjb = NULL;
Pobjb = static_cast <B *> (pobja );//The base class pointer is successfully converted into a subclass pointer.
Pobjb-> M =10;//In reality, pobj points to a Class A object.
//What will happen above? normally run in vc6.0 ...?

// If:

Pobjb = dynamic_cast <B *> (pobja );//Error base class A No virtual function does not constitute Polymorphism

Case 2: Dynamic_cast Conversion

 
ClassA
{
Public:
Virtual~ A (){} //Virtual function Polymorphism
};
ClassB:PublicA
{
Public:
IntM;
};

A * pobja =NewA ();
B * pobjb = NULL;
Pobjb = dynamic_cast <B *> (pobja );//Compiled
//Actual running result: pobjb = NULL//Dynamic_cast ensures invalid conversion and returns NULL

Dynamic_castIf the conversion fails, 0 is returned..

4. Role of virtual functions in dynamic_cast Conversion

Why do virtual functions need to be used to convert class pointers using dynamic_cast.

Dynamic_cast conversion is performed at runtime. during runtime conversion, you need to know the information of class objects (inheritance relationships, etc ).

How to get this information at runtime-virtual function table.

In the C ++ object model, the top part of the object instance is the virtual function table pointer,

This pointer can be used to obtain all the virtual functions of this class object,Including the parent class.

Because the derived class inherits the virtual function table of the base class, we can know the parent class of the Class Object through this virtual function table, during conversion, it can be used to determine whether the object has an inheritance relationship.

Therefore, it is very important for a virtual function to convert a base class pointer to a subclass pointer.

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.