The difference between Static_cast,dynamic_cast,reinterpret_cast and const_cast _c language

Source: Internet
Author: User

C-style Cast Example:
int i;
Double D;
i = (int) d;

The code above is the D of the type double, which is converted to an integer value by (int) d and assigned to the shape variable i (note that the value of D itself has not changed). This is the typical C-style type conversion.

The following is a simple program:

Copy Code code as follows:

#include <iostream>
using namespace Std;

int main (void)
{
int i;
Double d = 11.29;

i = (int) d;
cout << i << Endl;
cout << D << Endl;

return 0;
}

Output results:
11
11.29

We found that the D value itself did not change anything.

In simple cases, the above type conversion works well, but it is often not enough in C + + to ansi-c++ the four conversions defined by the new standard, namely static_cast, dynamic_cast, reinterpret_cast, and Const_ Cast At the same time in the C + + environment, the original C-style type conversion can still be used.

1) static_cast
Usage:
Static_cast <typeid> (expression)
Description:This operator converts expression to a typeid type, but does not have run-time type checking to ensure the security of the conversion.
Application:
A is used for a pointer or reference conversion between a base class and a derived class in a class hierarchy. Up-casting (It is safe to convert a pointer or reference of a derived class to a pointer or reference representation of a base class); Down-casting (a pointer or reference that converts a base class pointer or reference to a subclass) is unsafe.

b for conversion between basic data types, such as converting int to char, the security of this conversion is also guaranteed by the developer.

c) The null pointer can be converted to a null pointer of the target type.

D) Converts an expression of any type to a void type.
Note: static_cast cannot convert the const, Volitale, or __unaligned properties of expression.

2 dynamic_cast
usage:
dynamic_cast <typeid> (expression)
Description: This operator converts expression to an object of type typeID. typeID must be a pointer to a class, a reference to a class, or a void*. If the typeid is a pointer type of the class, then expression must also be a pointer, and if typeID is a reference, then expression must also be a reference. In general, dynamic_cast is used for type conversions of classes that have polymorphism (that is, classes that have virtual functions). The

Dynamic_cast relies on rtti information, and secondly, when converting, dynamic_cast checks whether the converted source object can actually be converted to the target type, not syntactically, but a real-world check. First look at the RTTI related part, in general, many compilers find the object's Rtti information through vtable, which means that if the base class has no virtual methods, it cannot judge the true type of the object that a base-class pointer variable refers to, when dynamic_cast can only be used to make a secure conversion. For example, convert from a derived class pointer to a base class pointer. And this kind of conversion does not need dynamic_cast to participate in fact. In other words, dynamic_cast is based on the information recorded in Rtti to determine whether the type conversion is legal. The

Purpose: is used primarily for up-casting and down-casting between class hierarchies and for cross conversion between classes. When Down-casting, dynamic_cast has the function of type checking, more secure than static_cast. Detection is performed at run time. If the converted pointer is not a valid, full object pointer to the request, the return value is null. When used with polymorphic types, it allows arbitrary implicit type conversions as well as the opposite process. However, unlike static_cast, in the latter case (note: The reverse process of an implicit conversion), dynamic_cast checks to see if the operation is valid. That is, it checks whether the conversion returns a valid, full object that is being requested.

Note: dynamic_cast cannot convert the const, Volitale, or __unaligned attributes of expression.

3) reinterpret_cast
Usage: reinterpret_cast <typeid> (expression)
Description: Converts a pointer to another type of pointer, also allows a pointer to be converted to an integer type, and vice versa. This operator is capable of converting between unrelated types. The operation result is simply a binary copy of the value from one pointer to another pointer, and the content pointed between the types does not do any type of checking and conversion. This is a cast. The use of a very high risk, use it with caution.
Note: reinterpret _cast cannot convert the const, Volitale, or __unaligned attributes of expression.

4) const_cast
Usage:const_cast<typeid> (expression)
Description: This type manipulates the const property of the passed object, or it is set or removed. Such as:
Class c{...}
Const c* A = new C;
c* B = const_cast<c*> (a);

If the above const_cast is converted to any other conversion, the compilation cannot pass, the confidence of the error is roughly as follows:
"... cannot convert from ' const Class C * ' to ' class C * '.

The following code is an example of a typical usage of the casting method in 4:

Copy Code code as follows:

#include <iostream>
using namespace Std;

Class Base
{
Public
int _base;
virtual void Printinfo ()
{
cout << _base << Endl;
}
};

Class Derived:public Base
{
Public
int _derived;
virtual void Printinfo ()
{
cout << _derived << Endl;
}
};

int main (void)
{
Base B1;
Derived D1;
int aint = 10;
Long along = 11;
float afloat = 11.11f;
Double adouble = 12.12;

derived* PD = static_cast<derived*> (&AMP;B1); Down-casting not safe.
base* PB = static_cast<base*> (&AMP;D1); Up-casting Security
derived& d = static_cast<derived&> (B1); Down-casting not safe.
base& B = static_cast<base&> (D1); Up-casting Security

aint = static_cast<int> (afloat); Basic Data type Conversions
void* sth = static_cast<void*> (&adouble); Converts a double pointer type to a void pointer type
double* bdouble = static_cast<double*> (STH); Converts a void pointer type to a double pointer type
cout << *bdouble << Endl;

base* PB1 = dynamic_cast<base*> (&AMP;D1);
derived* PD1 = dynamic_cast<derived*> (&AMP;B1); There are warning at compile time, run-time error

int bInt = reinterpret_cast<int> (PB1); Converts an address or pointer to an integer
cout << bInt << Endl;
PB1 = reinterpret_cast<base*> (bInt); Converts an integer to an address or pointer

int* cInt = reinterpret_cast<int*> (&afloat); The result of this conversion would be unexpected.
cout << (int) *cint << Endl;

Const base* bbase = new Base ();
base* cBase = const_cast<base*> (bbase);
base* dBase = dynamic_cast<base*> (bbase); cannot be compiled by
base* ebase = static_cast<base*> (bbase); cannot be compiled by
base* fbase = reinterpret_cast<base*> (bbase); cannot be compiled by

return 0;
}

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.