Static_cast and dynamic_cast coercion type conversions in C + + __c++

Source: Internet
Author: User
Tags square root

Objective

Speaking of C + + in the inheritance, polymorphism, virtual functions and other concepts, may be a lot of students have some understanding, but to say that really familiar with the students may not be a lot. In the recent process of programming, we learned about the hierarchical transformations of C + + types (this involves the relative probability of polymorphism and inheritance), it is usually possible to cast a built-in type in C, but it is not safe to do so, and in the C + + standard, there are two keywords in the type hierarchy conversion static_ Cast and dynamic_cast.

First, static_cast keywords (compile-time type check)

Usage: static_cast < Type-id > (expression), which converts expression to a type-id type, but does not have run-time type checking to guarantee the security of the conversion, which is mainly used in the following ways:

(1) For conversion between basic data types, if you convert an int to char and an int into an enum, the security of the conversion needs to be guaranteed by the developer (this can be understood to guarantee the accuracy of the data, that is, whether the programmer can guarantee the security of the program you want), such as when converting int to Char If Char does not have enough bits to hold the value of int (int>127 or int<-127), then static_cast is simply truncated and simply copies the lower 8 bits of the int to 8 bits of char and discards the highs directly.

(2) NULL pointer converted to target type

(3) Convert any type of expression type to void type

(4) is used for the conversion of pointers and references between the parent class and the subclass in the class hierarchy.

For the above point (4), there are two forms of conversion, the ascending conversion (subclass to the parent class), and the downlink transformation (the parent class to the subclass). For static_cast, the upstream conversion is safe, and downlink conversion is not safe, why. Because the conversion of the static_cast is brutal, it is only converted based on the information provided in the type conversion statement (type in angle brackets), which for the upstream conversion, because the subclass always contains all the data members and function members of the parent class. Therefore, a pointer object that converts from a subclass to a parent class can have no qualms about accessing its members (the parent class). And why the downlink conversion is not safe, because static_cast only at compile-time type persistence, there is no run-time type checking, the specific principle in the dynamic_cast explained.

Second, dynamic_cast keywords (run-time type check)

Usage: Same static_cast

Dynamic_cast is primarily used for the conversion of pointers and references between the parent class and subclasses in the class hierarchy, and because of the run-time type checking, the security of the downlink conversion can be guaranteed. That is, the converted correct type pointer is returned if the conversion succeeds, and Null is returned if the conversion fails, and it is said that Static_cast is not secure in the downlink conversion because it does not return null even if the conversion fails.

For uplink conversions, dynamic_cast and static_cast are the same.

For downlink conversion, when it comes to downlink conversion, one thing to understand is that in C + +, it is generally possible to refer to a subclass object with the parent pointer, such as parent* P1 = new Children (); However, this pointer can only access the data members and functions defined by the parent class, which is a static once came together in C + +, but generally does not define a subclass type pointer to a parent class object, such as children* P1 = new Parent; This method of definition does not conform to the habits of life and is cumbersome in programming. This explains also that in the uplink, the static_cast and dynamic_cast effects are the same, and both are safe, because the object being converted is generally a subclass type pointer to the subclass object, and in the downlink transformation, Because it is possible to define a parent class type pointer to a subclass object, while static_cast type checking only at compile time, and dynamic_cast is a run-time type check, it depends. The following is explained by code

[CPP] view Plain copy class Base {virtual void fun () {}};   Class Derived:public Base {}; Because of the need for downward conversion, you need to define a pointer base *p for a parent class type, but because the subclass inherits from the parent class, the parent class pointer can point to the parent class object, or to the subclass object, which is the point. If P points to a subclass object, both dynamic_cast and static_cast can convert successfully, as follows:

[CPP] view plain copy Base *p = new Derived ();   Derived *PD1 = static_cast<derived *> (P);   Derived *pd2 = dynamic_cast<derived *> (P); All of the above conversions will succeed.

However, if P is not pointing to a subclass object, it is a parent class object, as follows:

[CPP] view plain copy base *p = new Base;   Derived *pd3 = static_cast<derived *> (P); Derived *pd4 = dynamic_cast<derived *> (P);

In the above conversion, the static_cast conversion does not error at compile time, you can also return a subclass object pointer (hypothetical), but this is unsafe and can be problematic at run time because subclasses contain data and function members that are not in the parent class, and here you need to understand the literal meaning of the transformation and what the transformation is. Conversion is the conversion of an object from one type to another, and if you use PD3 to access a member of a subclass that has but not a parent class, an error of accessing the bounds will occur, causing the program to crash. dynamic_cast, which has run-time type checking, can check the type of P, and because the above conversion is unreasonable, it returns NULL.


Third, summary

There are only two types of hierarchical type conversions in C + +: Uplink and downlink

For the upward conversion, static_cast and dynamic_cast effect, are safe;

For downlink conversions: You must be sure that the data you want to convert is really the target type of data, that you need to be aware of whether the parent type pointer you want to convert is really pointing to a subclass object, and if so, static_cast and dynamic_cast can succeed; if not static_cast can return, However, it is unsafe and may have access-crossing errors, while dynamic_cast determines that the procedure cannot be converted and returns null during Run-time type checking.


Appendix:

First, review the C + + type conversions:

C + + type conversions are divided into: implicit type conversions and explicit type conversions

1th part. Implicit-type conversions

Also known as "standard conversions," includes the following:
1 Arithmetic conversion (arithmetic conversion): In the arithmetic expression of a mixed type, the widest data type becomes the target conversion type. int ival = 3;
Double dval = 3.14159;

Ival + dval; Ival is promoted to double type

2 A type expression is assigned to an object of another type: The target type is the type of the assigned object, int * pi = 0; 0 is converted to int * type
Ival = Dval; Double->int

Exception: No standard conversions exist for null pointer assignment to other specified type pointers, compilation error

3 An expression is passed as an argument to a function call when the formal parameter and argument types are inconsistent: the target transformation type is the type of the formal parameter extern double sqrt (double);

cout << "The square root of 2 is" << sqrt (2) << Endl;
2 promoted to double type: 2.0

4 Returns an expression from a function, the expression type is inconsistent with the return type: The target conversion type is the return type of the function double difference (int ival1, int ival2)
{
return ival1-ival2;
The return value is promoted to the double type
}


2nd part. Explicit type conversions
called Coercion type conversion (CAST)
C style: (Type-id)
C + + style: static_cast, dynamic_cast, reinterpret_cast, and const_cast.

The issue of coercion type conversions is discussed in many books, and the most detailed is the design and evolution of C + +, the father of C + +. The best solution is not to use the C-style coercion type conversion, but rather to use the standard C + + type conversion character: Static_cast, dynamic_cast. There are four types of conversion characters in standard C + +: static_cast, dynamic_cast, reinterpret_cast, and const_cast. Here's a description of them.

static_cast

Usage: static_cast < type-id > (expression)

Description: This operator converts expression to type- ID type, but there is no run-time type check to guarantee the security of the conversion.

Source: Why you need to static_cast a cast.
Condition 1:void Pointer-> Other type of pointer
Condition 2: Change the normal standard conversion
Condition 3: Avoid possible ambiguity in multiple conversions
It has several uses: for a pointer or reference conversion between a base class and a subclass in a class hierarchy. It is safe to perform an upward conversion (the pointer or reference of the handle class is converted to a base class representation), and it is unsafe to perform a downward conversion (converting the base class pointer or reference to a subclass pointer or reference) because there is no dynamic type checking. For conversions between basic data types, such as converting an int to char and converting an int to an enum. The security of this transformation also needs to be ensured by developers. Converts a void pointer to a pointer to a target type;

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.