Type Casting
  C++ : Documents : C++ Language Tutorial : Type Casting
  Search:
user pass [register]

javascript and cookies required

C++ Language Tutorial
Introduction
?Instructions for use
Basics of C++
?Structure of a program
?Variables. Data Types.
?Constants
?Operators
?Basic Input/Output
Control Structures
?Control Structures
?Functions (I)
?Functions (II)
Compound Data Types
?Arrays
?Character Sequences
?Pointers
?Dynamic Memory
?Data Structures
?Other Data Types
Object Oriented Programming
?Classes (I)
?Classes (II)
?Friendship and inheritance
?Polymorphism
Advanced Concepts
?Templates
?Namespaces
?Exceptions
?Type Casting
?Preprocessor directives
C++ Standard Library
?Input/Output with files
Document categories
Information about C++
C++ Language Tutorial
Additional Papers
User-contributed
cplusplus.com
documents
reference
sourcecodes
forum

Type Casting

Published by Juan Soulie
Last update on Nov 2, 2005 at 1:42am

Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:

Implicit conversion

Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:

 a=2000; b;b=a;

Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example:

 A {}; B { : B (A a) {} };A a;B b=a;

Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.

Explicit conversion

C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:

 a=2000; b;b = () a;    b =  (a);    

The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct:

  std; CDummy { i,j;}; CAddition { x,y;:CAddition ( a,  b) { x=a; y=b; } result() {  x+y;}}; main () {CDummy d;CAddition * padd;padd = (CAddition*) &d;cout << padd->result(); 0;}
                        

The program declares a pointer to CAddition, but then it assigns to it a reference to an object of another incompatible type using explicit type-casting:

padd = (CAddition*) &d;

Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member result will produce either a run-time error or a unexpected result.

In order to control these types of conversions between classes, we have four specific casting operators: dynamic_cast, reinterpret_cast, static_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.

dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)

The traditional type-casting equivalents to these expressions would be:

(new_type) expression
new_type (expression)

but each one with its own special characteristics:

dynamic_cast

dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

Therefore, dynamic_cast is always successful when we cast a class to one of its base classes:

 CBase { }; CDerived:  CBase { };CBase b; CBase* pb;CDerived d; CDerived* pd;pb = <CBase*>(&d);     pd = <CDerived*>(&b);  

The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.

When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:

  std; CBase {  dummy() {} }; CDerived:  CBase {  a; }; main () { {CBase * pba =  CDerived;CBase * pbb =  CBase;CDerived * pd;pd = <CDerived*>(pba); (pd==0) cout <<  << endl;pd = <CDerived*>(pbb); (pd==0) cout <<  << endl;}  (exception& e) {cout <<  << e.what();} 0;}
Null pointer on second type-cast

Compatibility note: dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers include this feature as an option which is disabled by default. This feature must be enabled for runtime type checking using dynamic_cast.

The code tries to perform two dynamic casts from pointer objects of type CBase* (pba and pbb) to a pointer object of type CDerived*, but only the second one is successful. Notice their respective initializations:

CBase * pba =  CDerived;CBase * pbb =  CBase;

Even though both are pointers of type CBase*, pba points to an object of type CDerived, while pbb points to an object of type CBase. Thus, when their respective type-castings are performed using dynamic_cast, pba is pointing to a full object of class CDerived, whereas pbb is pointing to an object of class CBase, which is an incomplete object of class CDerived.

When dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_alloc is thrown instead.

dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).

static_cast

static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.

 CBase {}; CDerived:  CBase {};CBase * a =  CBase;CDerived * b = <CDerived*>(a);

This would be valid, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.

static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:

 d=3.14159265; i = <>(d);

Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.

reinterpret_cast

reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.

It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.

The conversions that can be performed by reinterpret_cast but not by static_cast have no specific uses in C++ are low-level operations, whose interpretation results in code which is generally system-specific, and thus non-portable. For example:

 A {}; B {};A * a =  A;B * b = <B*>(a);

This is valid C++ code, although it does not make much sense, since now we have a pointer that points to an object of an incompatible class, and thus dereferencing it is unsafe.

const_cast

This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter:

  std; print ( * str){cout << str << endl;} main () {  * c = ;print ( < *> (c) ); 0;}
sample text

typeid

typeid allows to check the type of an expression:

typeid (expression)

This operator returns a reference to a constant object of type type_info that is defined in the standard header file <typeinfo>. This returned value can be compared with another one using operators == and != or can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member.

  std; main () { * a,b;a=0; b=0; ((a) != (b)){cout << ;cout <<  << (a).name() << ;cout <<  << (b).name() << ;} 0;}
a and b are of different types:a is: int *b is: int

When typeid is applied to classes typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object:

  std; CBase { f(){} }; CDerived :  CBase {}; main () { {CBase* a =  CBase;CBase* b =  CDerived;cout <<  << (a).name() << ;cout <<  << (b).name() << ;cout <<  << (*a).name() << ;cout <<  << (*b).name() << ;}  (exception& e) { cout <<  << e.what() << endl; } 0;}
a is: class CBase *b is: class CBase **a is: class CBase*b is: class CDerived

Notice how the type that typeid considers for pointers is the pointer type itself (both a and b are of type class CBase *). However, when typeid is applied to objects (like *a and *b) typeid yields their dynamic type (i.e. the type of their most derived complete object).

If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception.

Previous:
Exceptions

index
Next:
Preprocessor directives
© The C++ Resources Network, 2000-2005 - All rights reserved
posted on 2006-04-13 11:27 horily 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/horily/archive/2006/04/13/374109.html

Type Casting相关推荐

  1. [翻译]JavaScript秘密花园 - Type Casting,undefined,eval,setTimeout,Auto Semicolon Insertion - 全部完成PDF打包下载

    JavaScript Garden - 原文 JavaScript Garden - 中文翻译 PDF打包下载 类型转换 JavaScript 是弱类型语言,所以会在任何可能的情况下应用强制类型转换. ...

  2. js 字符串转换成数字的 三种方法

    在js读取文本框或者其它表单数据的时候获得的值是字符串类型的,例如两个文本框a和b,如果获得a的value值为11,b的value值为9 ,那么a.value要小于b.value,因为他们都是字符串形 ...

  3. javassist学习笔记

    2019独角兽企业重金招聘Python工程师标准>>> 介绍:www.javassist.org/ javassist.ASM 对比 1.javassist是基于源码级别的API比基 ...

  4. 微信小程序开发之不能使用eval函数的问题

    2019独角兽企业重金招聘Python工程师标准>>> 一 eval函数问题 JavaScript中的eval函数是颇受开发者争议的问题之一,问题主要在于其可能导致的不安全性.有关此 ...

  5. 对象存在性检测集中管理

    在中大型业务系统中, 常常需要从数据库中查询某个实体对象. 在进行处理之前, 必须先检测该实体是否存在,以增强系统的健壮性. 不过, 检测代码充斥在主业务流程中又会大大降低业务逻辑的清晰性, 最好集中 ...

  6. 10条PyTorch避坑指南

    点击上方"视学算法",选择加"星标" 重磅干货,第一时间送达 本文转载自:机器之心  |  作者:Eugene Khvedchenya 参与:小舟.蛋酱.魔王 ...

  7. Swift互用性:采用Cocoa设计模式(Swift 2.0版)-b

    本页包含内容: 委托(Delegation) 错误处理(Error Handling) 键值观察(Key-Value Observing) Target-Action模式(Target-Action) ...

  8. iOS:消除项目中警告

    引言: 在iOS开发过程中, 我们可能会碰到一些系统方法弃用, weak.循环引用.不能执行之类的警告. 有代码洁癖的孩子们很想消除他们, 今天就让我们来一次Fuck 警告!! 首先学会基本的语句: ...

  9. 你不懂js系列学习笔记-类型与文法- 04

    第四章:强制转换 原文:You-Dont-Know-JS 1. 转换值 将一个值从一个类型明确地转换到另一个类型通常称为"类型转换(type casting)",当这个操作隐含地完 ...

最新文章

  1. 论防止爆T的重要性:N相关孪生素数
  2. php 贝瑟尔曲线,贝塞尔曲线的应用详解
  3. redis和mysql内存数据库性能_Redis高性能内存数据库
  4. CNCC技术论坛丨联邦学习冲刺人工智能“最后一公里”!
  5. linux的磁盘文件系统格式怎么看,linux如何下查看磁盘分区的文件系统格式?
  6. FreeRTOS知识点
  7. 操作系统(十七)调度算法(二)
  8. 02:输出最高分数的学生姓名
  9. [leetcode]Subsets @ Python
  10. 福昕风腾pdf导出为html,福昕风腾PDF套件快速指引.pdf
  11. (BFS+hash去重)八数码问题
  12. 专题导读:大数据整理
  13. devops_您的DevOps阅读心愿单的10本书
  14. python资源分配算法_DRL based Resource Allocation Framework
  15. [LeetCode]129. Sum Root to Leaf Numbers路径数字求和
  16. python 转成摩尔斯电码_【无线电史话】比莫尔斯电码更直观 | 1919年的护林员通过Myer码传递信息...
  17. Win_Server_2003-2016_加密勒索事件必打补丁合集
  18. 《东周列国志》第七十一回 晏平仲二桃杀三士 楚平王娶媳逐世子
  19. 计算机键盘图 指法,键盘指法练习图
  20. 企业自动运行系统——价格策略

热门文章

  1. [待总结]redmine
  2. 如何定位死循环或高CPU使用率(linux)
  3. php透明颜色的代码,PHP imagecolorallocatealpha - 为一幅图像分配颜色和透明度
  4. python加密程序_Python加密程序
  5. mysql linux文件_MySQL在Linux系统下配置文件详解
  6. Java开发中遇到具有挑战的事_Java并发编程的挑战:遇到的问题及如何解决
  7. 虚拟化运维工具对金融行业的解决方案
  8. c# 正则表达式 html标签,C#匹配HTML标签,正则表达式谁会?
  9. rdf mysql持久化l_Jena 利用数据库保存,持久化本体
  10. 视觉设计师跟平面设计_使设计具有视觉吸引力