29-03-2014, 10:51 AM
C++ Typecasting Part 1
Typecasting Part.docx (Size: 21.46 KB / Downloads: 10)
Implicit conversion
Almost every compiler makes use of what is called automatic typecasting. It automatically converts one type into another type. If the compiler converts a type it will normally give a warning. For example this warning: conversion from ‘double’ to ‘int’, possible loss of data.
The problem with this is, that you get a warning (normally you want to compile without warnings and errors)
and you are not in control. With control we mean, you did not decide to convert to another type, the compiler did. Also the possible loss of data could be unwanted.
Explicit conversion
The C and C++ languages have ways to give you back control. This can be done with what is called an explicit conversion. Sure you may still lose data, but you decide when to convert to another type and you don’t get any compiler warnings.
Four typecast operators
The C++ language has four typecast operators:
static_cast
reinterpret_cast
const_cast
dynamic_cast
Static_cast
Automatic conversions are common in every C++ program. You have:
Standard conversion. For instance: from short to int or from int to float.
User defined conversions (Class conversions.)
Conversion from derived class to base class.
(Take a look at the inheritance tutorial)
Runtime Type Information (RTTI)
Runtime Type Information (RTTI) is the concept of determining the type of any variable during execution (runtime.) The RTTI mechanism contains:
The operator dynamic_cast
The operator typeid
The struct type_info
RTTI can only be used with polymorphic types. This means that with each class you make, you must have at least one virtual function (either directly or through inheritance.)
Compatibility note: On some compilers you have to enable support of RTTI to keep track of dynamic types.
So to make use of dynamic_cast (see next section) you have to enable this feature. See you compiler documentation for more detail.
Typeid and typ_info
If a class hierarchy is used then the programmer doesn’t have to worry (in most cases) about the data-type of a pointer or reference, because the polymorphic mechanism takes care of it. In some cases the programmer wants to know if an object of a derived class is used. Then the programmer can make use of dynamic_cast. (If the dynamic cast is successful, then the pointer will point to an object of a derived class or to a class that is derived from that derived class.) But there are circumstances that the programmer (not often) wants to know the prizes data-type. Then the programmer can use the typeid operator.