BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Type Cast Operators - 2020

cplusplus_icon.png




Bookmark and Share





bogotobogo.com site search:




Type-Conversion Operators

Here is the list of type-conversions.


  1. a = dynamic_cast<T*>(p)
    Try to convert p into a T*. It may return 0

  2. a = dynamic_cast<T&>(*p)
    Try to convert *p into a T&. It may throw bad_cast

  3. a = static_cast<T>(p)
    Convert p into a T if a T can be conterted into p's type.

  4. a = reinterpret_cast<T>(p)
    Convert p into a T represented by the same bit pattern.

  5. a =const_cast<T>(p)
    Convert p into a T by adding or subtracting const.

  6. a = (T)v
    C-style cast.

  7. a = T(v)
    Functional cast.

Which one compiles successfully?

As a preview, take the following code and guess which line compiles.

struct Foo{};
struct Bar{};

int main(int argc, char** argv)
{
    Foo* f = new Foo;

    Bar* b1 = f;                              // (1)
    Bar* b2 = static_cast<Bar*>(f);           // (2)
    Bar* b3 = dynamic_cast<Bar*>(f);          // (3)
    Bar* b4 = reinterpret_cast<Bar*>(f);      // (4)
    Bar* b5 = const_cast<Bar*>(f);            // (5)

    return 0;
}

Answer is only line (4) compiles without any complain. Only reinterpret_cast can be used to convert a pointer to an object to a pointer to an unrelated object type. The dynamic_cast would fail at run-time, however on most compilers it will also fail to compile because there are no virtual functions in the class of the pointer being casted.



const_cast

const_cast is typically used to cast away the constness of objects. It is the only C++ style that can do this.

The syntax is:

const_cast < type-name > (expression)

The reason for this operator is that we may have a need for a value that is constant most of the time but that can be changed occasionally. In such a case, we can declare the value as const and use const_cast when we need to alter the value.

Here is a simple example:

#include <iostream>
#include <cstring>
using namespace std;
int main () {
  string str("A123456789");
  const char *cstr = str.c_str();
  char *nonconst_cstr  = const_cast<char *> (cstr) ; 
  *nonconst_cstr ='B';
  cout << nonconst_cstr << endl;
  return 0;
}

Because we casted away the constness of the string, we were able to modify the string from "A123456789" to "B1234567889".





reinterpret_cast

reinterpret_cast is intended for low-level casts that yield implementation-dependent and it would not be portable.

This cast is used for reinterpreting a bit pattern. It is not guaranteed to be portable. In fact, it is best to assume that reinterpret_cast is not portable at all. A typical example is an int-to-pointer to get a machine address into a program:

Register* a = reinterpret_cast<Register*>(0xfa);

This example is the typical use of a reinterpret_cast. We are telling the compiler that the part of memory starting with 0xfa is to be considered a Register.

It 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.

We can cast a pointer type to an integer type that's large enough to hold the pointer representation, but we can't cast a pointer to a smaller integer type or to a floating-point type. The format in which this integer value represents a pointer is platform-specific. We can't cast a function pointer to a data pointer or vice versa.

The syntax is:

reinterpret_cast < type-name > (expression)

Here is an example code:

#include <iostream>
using namespace std;

struct data {
	short a; 
	short b;
};

int main () {
	long value = 0xA2345678;
	data* pdata = reinterpret_cast<data*> (&value;);
	cout << pdata->a << endl;
	return 0;
}

Output on my machine: 22136 which is 2 bytes of value.

Another example might be:

class A {};
class B {};

int main() 
{
	A * pA = new A;
	B * pB = reinterpret_cast<B*>(pA);
}


In the following code (b1-b5), only Bar* b5 = reinterpret_cast<Bar*> compiles.

struct Foo {};
struct Bar {};

int main()
{
	Foo* f = new Foo;

	Bar* b1 = f;
	Bar* b2 = static_cast<Bar*>(f);
	Bar* b3 = dynamic_cast<Bar*>(f);
	Bar* b4 = const_cast<Bar*>(f);
	Bar* b5 = reinterpret_cast<Bar*>(f);

	return 0;
}

Only reinterpret_cast can be used to convert a pointer to an object to a pointer to an unrelated object type. The dynamic cast would fail at run-time, however on most compilers it will also fail to compile because there are no virtual functions in the class of the pointer being casted.



Pointer comparison

Normally, the pointer comparison between different types are undefined. Here is the example of using reinterpret_cast for pointer comparison.

#include <iostream>

class A{};
class B{};
class C:public A, public B{};

int main()
{
    C d;
    A *a = &d;
    B *b = &d;

    bool bool1 = reinterpret_cast<char*>(a) == reinterpret_cast<char*>(&d;);
    bool bool2 = b == &d;
    bool bool3 = reinterpret_cast<char*>(a) == reinterpret_cast<char*>(b);

    std::cout << bool1 << bool2 << bool3 << std::endl; // 110

    return 0;
}

Base pointer (a and b) and the address of the derived object &d; are equal but a and b are different as expected.

Here is one of the threads related to the comparing pointers. How to compare pointers?.





static_cast

static_cast can be used to force implicit conversions such as non-const object to const, int to double. It can be also be used to perform the reverse of many conversions such as void* pointers to typed pointers, base pointers to derived pointers. But it cannot cast from const to non-const object. This can only be done by const_cast operator.

The syntax is:

	static_cast < type-name > (expression)

It's valid only if type_name can be converted implicitly to the same type that expression has, or vise versa. Otherwise, the type cast is an error.

class Base {};
class Derived : public Base {};
class UnrelatedClass {};

int main() 
{
	Base base;
	Derived derived;

	// #1: valid upcast
	Base *pBase = static_cast<Base *>(&derived;);  

	// #2: valid downcast
	Derived *pDerived = static_cast<Derived *> (&base;);

	// #3: invalid, between unrelated classes
	UnrelatedClass *pUnrelated 
		= static_cast<UnrelatedClass *> (&derived;);
}

In the example, the conversion from Base to Derived and Derived to Base are valid, but a conversion from Derived to UnrelatedClass is disallowed.

The #1 conversion here is valid because an upcast can be done explicitly. The #2 conversion, from a base-class pointer to a derived-class pointer, can't be done without an explicit type conversion. But because the type cast in the other direction can be made without a type cast, it's valid to use static_cast for a downcast. However, pDerivded would point to an incomplete object of the class and could lead to runtime errors if dereferenced.

As we saw in the example, 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.



dynamic_cast

dynamic_cast is used to perform safe downcasting, i.e., to determine whether an object is of a particular type in an inheritance hierarchy. It is the only cast that may have a significant runtime cost.

Look at the dynamic_cast of C++ Tutorial - dynamic_cast.



Casting - pros and cons

This is from Google C++ Style Guide.

C++ introduced a different cast system from C that distinguishes the types of cast operations. Use C++ casts like static_cast<>(). Do not use other cast formats like int y = (int)x; or int y = int(x);.

  1. Pros
    The problem with C casts is the ambiguity of the operation; sometimes we are doing a conversion (e.g., (int)3.5) and sometimes we are doing a cast (e.g., (int)"hello"); C++ casts avoid this. Additionally C++ casts are more visible when searching for them.
  2. Cons
    The syntax is nasty.
  3. Decision
    Do not use C-style casts. Instead, use these C++-style casts.
    1. Use static_cast as the equivalent of a C-style cast that does value conversion, or when we need to explicitly up-cast a pointer from a class to its superclass.
    2. Use const_cast to remove the const qualifier.
    3. Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if we know what we are doing and we understand the aliasing issues.
    4. For dynamic_cast, visit RTTI - pros and cons.




KeumKangKaChangOri





Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master