Four types of forced type conversions in C + + basic usage and usage scenarios

Source: Internet
Author: User

Type conversions in C:

The first thing to start with is the C language. We are used to using the C-like type conversion because it is powerful and simple.

There are two main types:

    • (new-type) expression

    • New-type (expression)

C-style conversion format is simple, but there are many drawbacks:

1. The conversion is too arbitrary and can be converted between any type. You can convert a pointer to a const object into a pointer to a non-const object, convert a pointer to a base class object into a pointer to a derived class object, the gap between these transformations is very large, but the traditional C-style type conversion does not differentiate between these exponentially.

2.C-style conversions do not have uniform keywords and identifiers. For large systems, code troubleshooting is easy to omit and ignore.

Type conversions in C + +:

The C + + style perfectly solves the above two problems. 1. The type conversion is subdivided, and four different types of conversions are provided to support the conversion of different requirements; 2. Type conversion has a uniform identifier, which facilitates code troubleshooting and inspection. These four conversions are described below: static_cast, dynamic_cast, Const_cast, and Reinterpreter_cast.

    • Static_cast, the name is understood to be a static type conversion. such as int converted to char.

    • dynamic_cast, the name is understood to be a dynamic type conversion. such as a polymorphic type conversion between a subclass and a parent class.

    • Const_cast, the literal understanding is to go to the const attribute.

    • Reinterpreter_cast, only the type is re-interpreted, but there is no binary conversion.

First, static_cast conversion

1. Basic usage : static_cast expression

2. Usage Scenarios :

A, the conversion of a pointer or reference between a base class and a derived class in a class hierarchy

Upstream conversions (derived classes---base classes) are safe;

Downstream conversions (base-to-derived classes) are unsafe because there is no dynamic type checking.

b, for conversions between basic data types, such as converting int to char, this poses a security issue that is guaranteed by the programmer

c. Convert null pointer to null pointer of target type

D. Convert any type of expression to void type

3. Usage features

A, the main implementation of non-polymorphic conversion operations to replace the usual conversion operations in C

b, implicit conversions are recommended to use static_cast to mark and replace

int n = 6;double d = static_cast<double> (n); Basic type conversion int *PN = &n;double *d = static_cast<double *> (&n)//unrelated type pointer conversion, compilation error void *p = Static_cast<void *&G t; (PN); Convert any type to void type

Second, dynamic_cast conversion

1. Basic usage : dynamic_cast expression

2. usage Scenario : Only use Dynamic_cast,type-id when converting between derived classes must be a class pointer, class reference, or void*.

3. Usage features :

A, the base class must have a virtual function, because dynamic_cast is a run-time type check, requires run-time type information, and this information is stored in the virtual function table of the class, only one class defined the virtual function, there will be a virtual function table (if a class does not have virtual functions, then in general sense, The designer of this class does not want it to be a base class).

b, for the downstream conversion, the dynamic_cast is safe (when the type is inconsistent, the conversion is a null pointer), and static_cast is unsafe (when the type is inconsistent, the conversion is the wrong meaning of the pointer, may result in memory, illegal access and other problems)

C, dynamic_cast can also be cross-converted

Class BaseClass {Public:int m_inum; virtual void foo () {};//base class must have a virtual function.  Maintain multiple features to use Dynamic_cast};class derivedclass:public baseclass {Public:char *m_szname[100];  void Bar () {};}; baseclass* PB = new DerivedClass ();D erivedclass *pd1 = Static_cast<derivedclass *> (pb);//Sub-class, parent class, static type conversion, Correct but not recommended derivedclass *PD2 = Dynamic_cast<derivedclass *> (pb);//subclass, parent class, dynamic type conversion, correct baseclass* PB2 = new BaseClass () ;//Parent class--subclass, static type conversion, Danger! Access subclasses M_szname members out of bounds derivedclass *pd21 = Static_cast<derivedclass *> (PB2);//parent class, subclass, dynamic type conversion, secure. The result is nullderivedclass *pd22 = Dynamic_cast<derivedclass *> (PB2);

Iii. Conversion of Const_cast

1. Basic usage : const_castexpression

2. Usage Scenarios :

A, constant pointer is converted to a very pointer, and still points to the original object

B, constant reference is converted to a very reference, and still points to the original object

3. Usage features :

A, Cosnt_cast is the only translator in four type conversions that can manipulate constants

b, removal of the constant is a dangerous action, try to avoid the use. A particular scenario is when a class provides overloading by const, which is typically a very const_cast function call that converts a parameter to a constant, then calls the constant function, then gets the result and then calls Const_cast to remove the constant.

struct SA {int i;}; Const SA RA;//RA.I = 10; Modify the const type directly, compile error SA &RB = const_cast<sa&> (RA); rb.i = 10;

Iv. Conversion of Reinterpret_cast

1. Basic usage : reinterpret_castexpression

2. usage Scenario : No need to use this translator, high-risk operation

3. Usage features :

A, reinterpret_cast is the data from the bottom of the re-interpretation, relying on the specific platform, the portability of poor

B, reinterpret_cast can convert an integer to a pointer, or you can convert a pointer to an array

C, reinterpret_cast can be used in pointers and references for unscrupulous conversion

int dosomething () {return 0;};/ /funcptr is a pointer to a function that has no arguments, a return value of type voidtypedef void (*funcptr) (), and an array of//10 funcptrs pointers Let's assume you want (for some inexplicable reason) to put a pointer to the following function in//into the Funcptrarray array: funcptr funcptrarray[10];funcptrarray[0] = &dosomething;/ /Compile Error! Type mismatch, reinterpret_cast can let the compiler look at them your way: funcptrarrayfuncptrarray[0] = reinterpret_cast<funcptr> (& dosomething);//conversion between different function pointer types

Summarize:

Go to the const attribute with const_cast.

Basic type conversion with static_cast.

A type conversion between polymorphic classes is used with Daynamic_cast.

Different types of pointer-type conversions with Reinterpreter_cast.

Related articles:

Coercion type conversions for C + +

C # Tutorial C # type Conversion

Related videos:

php automatic type conversion of data type conversions

Related Article

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.