Top 18 Static_Cast Reinterpret_Cast 11501 People Liked This Answer

You are looking for information, articles, knowledge about the topic nail salons open on sunday near me static_cast reinterpret_cast on Google, you do not find the information you need! Here are the best content compiled and compiled by the https://chewathai27.com/to team, along with other related topics such as: static_cast reinterpret_cast Reinterpret_cast vs static_cast, Dynamic_pointer_cast, Difference between static_cast and reinterpret_cast in c++, Reinterpret_cast C++, Static_cast in C++, Dynamic_cast, Static_cast to void, C style cast

Table of Contents

What is reinterpret_cast used for?

The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function.

When should I use static_cast?

This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc.

Why is static_cast better than C style cast?

In short: static_cast<>() gives you a compile time checking ability, C-Style cast doesn’t. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is’nt. Intentions are conveyed much better using C++ casts.

What static_cast is actually doing?

In short, static_cast<> will try to convert, e.g., float-to-integer, while reinterpret_cast<> simply changes the compiler’s mind to reconsider that object as another type.

When should I use Reinterpret_cast?

Purpose for using reinterpret_cast

It is used when we want to work with bits. If we use this type of cast then it becomes a non-portable product. So, it is suggested not to use this concept unless required. It is only used to typecast any pointer to its original type.

What is static_cast int in C++?

static_cast in C++

The static_cast is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coercion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes.

Does static_cast take time?

static_cast MAY take time at run-time. For example, if you convert int to float then work is required. Usually casting pointers does not require any run-time cost.

Can a static_cast fail?

static_cast can’t throw exception since static_cast is not runtime cast, if some cannot be casted, code will not compiles. But if it compiles and cast is bad – result is undefined.

Is dynamic casting bad?

dynamic_cast is “bad design” for the simple reason that it violates this purpose, since you need your object to be of some derived type, so it doesn’t suffice to know the base type of it. That being said it still has its use (especially as the world isn’t as simple as Java likes it to be).

Can I use static_cast in C?

Static casts are only available in C++. Static casts can be used to convert one type into another, but should not be used for to cast away const-ness or to cast between non-pointer and pointer types.

Which is C++ style type casting?

C++ provides a variety of ways to cast between types: static_cast. reinterpret_cast. const_cast.

What is dynamic cast?

Dynamic Cast: A cast is an operator that converts data from one type to another type. In C++, dynamic casting is mainly used for safe downcasting at run time. To work on dynamic_cast there must be one virtual function in the base class.

What happens if static_cast fails?

If static_cast fails you will get a compile error and the program executable will never even be built.

What is difference between static_cast and dynamic_cast?

static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.

Can static_cast return null?

The static_cast operator converts a null pointer value to the null pointer value of the destination type. Any expression can be explicitly converted to type void by the static_cast operator. The destination void type can optionally include the const , volatile , or __unaligned attribute.

What is C style cast?

C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.

What is Dynamic_cast in C++ with example?

The dynamic_cast operator ensures that if you convert a pointer to class A to a pointer to class B , the object of type A pointed to by the former belongs to an object of type B or a class derived from B as a base class subobject.

How do you cast in C++?

Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make ‘a’ function as a char.

What is Uintptr_t?

uintptr_t is an unsigned integer type that is capable of storing a data pointer. Which typically means that it’s the same size as a pointer. It is optionally defined in C++11 and later standards.


Casting in C++
Casting in C++


c++ – When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used? – Stack Overflow

  • Article author: stackoverflow.com
  • Reviews from users: 45115 ⭐ Ratings
  • Top rated: 4.2 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about c++ – When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used? – Stack Overflow static_cast is the first cast you should attempt to use. … reinterpret_cast is the most dangerous cast, and should be used very sparingly. …
  • Most searched keywords: Whether you are looking for c++ – When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used? – Stack Overflow static_cast is the first cast you should attempt to use. … reinterpret_cast is the most dangerous cast, and should be used very sparingly.
  • Table of Contents:

10 Answers
10

Not the answer you’re looking for Browse other questions tagged c++ pointers casting c++-faq or ask your own question

c++ - When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used? - Stack Overflow
c++ – When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used? – Stack Overflow

Read More

C H A P T E R 9 – Cast Operations

  • Article author: docs.oracle.com
  • Reviews from users: 34218 ⭐ Ratings
  • Top rated: 4.1 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about C H A P T E R 9 – Cast Operations
    This chapter discusses the newer cast operators in the C++ standard: const_cast , reinterpret_cast , static_cast , and dynamic_cast . …
  • Most searched keywords: Whether you are looking for C H A P T E R 9 – Cast Operations
    This chapter discusses the newer cast operators in the C++ standard: const_cast , reinterpret_cast , static_cast , and dynamic_cast .
  • Table of Contents:

91 const_cast

92 reinterpret_cast

93 static_cast

94 Dynamic Casts

C H A P T E R    9 - Cast Operations
C H A P T E R 9 – Cast Operations

Read More

reinterpret_cast Operator | Microsoft Docs

  • Article author: docs.microsoft.com
  • Reviews from users: 46340 ⭐ Ratings
  • Top rated: 3.1 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about reinterpret_cast Operator | Microsoft Docs Updating …
  • Most searched keywords: Whether you are looking for reinterpret_cast Operator | Microsoft Docs Updating Learn more about: reinterpret_cast Operator
  • Table of Contents:

Syntax

Remarks

See also

Feedback

reinterpret_cast Operator | Microsoft Docs
reinterpret_cast Operator | Microsoft Docs

Read More

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++?

  • Article author: www.tutorialspoint.com
  • Reviews from users: 26994 ⭐ Ratings
  • Top rated: 4.9 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++? Updating …
  • Most searched keywords: Whether you are looking for When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++? Updating When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++? – const_castcan be used to remove or add const to a variable. This can be …C, C++, Python, Java, HTML, CSS, JavaScript, SQL, PHP, jQuery, XML, DOM, Bootstrap, Tutorials, Articles, Programming, training, learning, quiz, preferences, examples, code
  • Table of Contents:

const_cast

static_cast

dynamic_cast

reinterpret_cast

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++?
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++?

Read More

c++ – What is the difference between static_cast<> and C style casting? – Stack Overflow

  • Article author: stackoverflow.com
  • Reviews from users: 49356 ⭐ Ratings
  • Top rated: 4.4 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about c++ – What is the difference between static_cast<> and C style casting? – Stack Overflow Updating …
  • Most searched keywords: Whether you are looking for c++ – What is the difference between static_cast<> and C style casting? – Stack Overflow Updating
  • Table of Contents:

7 Answers
7

Your Answer

Not the answer you’re looking for Browse other questions tagged c++ casting static-cast or ask your own question

c++ - What is the difference between static_cast<> and C style casting? – Stack Overflow” style=”width:100%”><figcaption>c++ – What is the difference between static_cast<> and C style casting? – Stack Overflow</figcaption></figure>
<p style=Read More

What static_cast<> is actually doing – CodeProject

  • Article author: www.codeproject.com
  • Reviews from users: 10513 ⭐ Ratings
  • Top rated: 3.0 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about What static_cast<> is actually doing – CodeProject Updating …
  • Most searched keywords: Whether you are looking for What static_cast<> is actually doing – CodeProject Updating An article discussing about static_cast<> and reinterpret_cast<>.VC6, VC7.0, VC7.1, VC8.0, C++, Windows, Visual-Studio, Dev, Intermediate
  • Table of Contents:

Introduction

Generic Types

Pointer Types

Case 1 Casting between unrelated classes

Case 2 Casting to related classes

Case 3 Casting back and forth between void

Footnote

References

History

License

Share

About the Author

Comments and Discussions

What static_cast<> is actually doing – CodeProject” style=”width:100%”><figcaption>What static_cast<> is actually doing – CodeProject</figcaption></figure>
<p style=Read More

static_cast Vs reinterpret_cast

  • Article author: social.msdn.microsoft.com
  • Reviews from users: 33071 ⭐ Ratings
  • Top rated: 3.5 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about
    static_cast Vs reinterpret_cast
    static_cast only allows conversions like int to float or base pointer to derived pointer. reinterpret_cast allows anything, that’s … …
  • Most searched keywords: Whether you are looking for
    static_cast Vs reinterpret_cast
    static_cast only allows conversions like int to float or base pointer to derived pointer. reinterpret_cast allows anything, that’s …
  • Table of Contents:

    static_cast Vs reinterpret_cast
static_cast Vs reinterpret_cast

Read More

static_cast Vs reinterpret_cast

  • Article author: xianbao-qian.medium.com
  • Reviews from users: 37094 ⭐ Ratings
  • Top rated: 3.2 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about
    static_cast Vs reinterpret_cast
    In C++, reinterpret_cast, static_cast and const_cast is very common. const_cast is pretty easy to understand as it doesn’t change the memory layout and just … …
  • Most searched keywords: Whether you are looking for
    static_cast Vs reinterpret_cast
    In C++, reinterpret_cast, static_cast and const_cast is very common. const_cast is pretty easy to understand as it doesn’t change the memory layout and just …
  • Table of Contents:

    static_cast Vs reinterpret_cast
static_cast Vs reinterpret_cast

Read More

How to explain the differences among static_cast, reinterpret_cast, const_cast, and dynamic_cast to a new C++ programmer – Quora

  • Article author: www.quora.com
  • Reviews from users: 1497 ⭐ Ratings
  • Top rated: 4.2 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about How to explain the differences among static_cast, reinterpret_cast, const_cast, and dynamic_cast to a new C++ programmer – Quora How do you explain the differences among static_cast, reinterpret_cast, const_cast, and dynamic_cast to a new C++ programmer? …
  • Most searched keywords: Whether you are looking for How to explain the differences among static_cast, reinterpret_cast, const_cast, and dynamic_cast to a new C++ programmer – Quora How do you explain the differences among static_cast, reinterpret_cast, const_cast, and dynamic_cast to a new C++ programmer? static_cast It can be used for any normal conversion between types, conversions that rely on static (compile-time) type information. This includes any casts between numeric types (for instance : from short to int or from int to float), casts of…
  • Table of Contents:
How to explain the differences among static_cast, reinterpret_cast, const_cast, and dynamic_cast to a new C++ programmer - Quora
How to explain the differences among static_cast, reinterpret_cast, const_cast, and dynamic_cast to a new C++ programmer – Quora

Read More

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++?

  • Article author: www.tutorialspoint.com
  • Reviews from users: 36970 ⭐ Ratings
  • Top rated: 4.8 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++? When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++? · const_cast. can be used to remove or add const to a … …
  • Most searched keywords: Whether you are looking for When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++? When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++? · const_cast. can be used to remove or add const to a … When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++? – const_castcan be used to remove or add const to a variable. This can be …C, C++, Python, Java, HTML, CSS, JavaScript, SQL, PHP, jQuery, XML, DOM, Bootstrap, Tutorials, Articles, Programming, training, learning, quiz, preferences, examples, code
  • Table of Contents:

const_cast

static_cast

dynamic_cast

reinterpret_cast

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++?
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used in C++?

Read More

Khi nào nên sử dụng static_cast, Dynamic_cast, const_cast và reinterpret_cast?

  • Article author: helpex.vn
  • Reviews from users: 20734 ⭐ Ratings
  • Top rated: 3.9 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about Khi nào nên sử dụng static_cast, Dynamic_cast, const_cast và reinterpret_cast? Các cách sử dụng thích hợp của: static_cast dynamic_cast const_cast reinterpret_cast Diễn viên kiểu C (type)value Diễn viên theo phong cách chức năng … …
  • Most searched keywords: Whether you are looking for Khi nào nên sử dụng static_cast, Dynamic_cast, const_cast và reinterpret_cast? Các cách sử dụng thích hợp của: static_cast dynamic_cast const_cast reinterpret_cast Diễn viên kiểu C (type)value Diễn viên theo phong cách chức năng … Các cách sử dụng thích hợp của: static_cast dynamic_cast const_cast reinterpret_cast Diễn viên kiểu C (type)value Diễn viên theo phong cách chức năng type(value) Làm thế nào để một người…c++,pointers,casting,c++-faq
  • Table of Contents:
Khi nào nên sử dụng static_cast, Dynamic_cast, const_cast và reinterpret_cast?
Khi nào nên sử dụng static_cast, Dynamic_cast, const_cast và reinterpret_cast?

Read More

reinterpret_cast conversion – cppreference.com

  • Article author: en.cppreference.com
  • Reviews from users: 27695 ⭐ Ratings
  • Top rated: 4.0 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about reinterpret_cast conversion – cppreference.com Unlike static_cast, but like const_cast, the reinterpret_cast expression does not compile to any CPU instructions (except when converting … …
  • Most searched keywords: Whether you are looking for reinterpret_cast conversion – cppreference.com Unlike static_cast, but like const_cast, the reinterpret_cast expression does not compile to any CPU instructions (except when converting …
  • Table of Contents:
reinterpret_cast conversion - cppreference.com
reinterpret_cast conversion – cppreference.com

Read More

How do you explain the differences among static_cast, reinterpret_cast, const_cast, and… | MoocLab – Connecting People to Online Learning

  • Article author: www.mooclab.club
  • Reviews from users: 20221 ⭐ Ratings
  • Top rated: 4.4 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about How do you explain the differences among static_cast, reinterpret_cast, const_cast, and… | MoocLab – Connecting People to Online Learning static_cast performs implicit conversions, the reverses of implicit standard conversions, and (possibly unsafe) base to derived conversions. · reinterpret_cast … …
  • Most searched keywords: Whether you are looking for How do you explain the differences among static_cast, reinterpret_cast, const_cast, and… | MoocLab – Connecting People to Online Learning static_cast performs implicit conversions, the reverses of implicit standard conversions, and (possibly unsafe) base to derived conversions. · reinterpret_cast … Brian Bi

    Why are they really needed?
    Good question! Actually, this is the key to understanding why C++ has four different casts.

    In C there is only a…

  • Table of Contents:
How do you explain the differences among static_cast, reinterpret_cast, const_cast, and... | MoocLab - Connecting People to Online Learning
How do you explain the differences among static_cast, reinterpret_cast, const_cast, and… | MoocLab – Connecting People to Online Learning

Read More

C++ static_cast,dynamic_cast,const_cast and reinterpret_cast (four types of conversion operators)

  • Article author: programmer.ink
  • Reviews from users: 45271 ⭐ Ratings
  • Top rated: 3.1 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about C++ static_cast,dynamic_cast,const_cast and reinterpret_cast (four types of conversion operators) reinterpret_cast can be consered as static_ A supplement to cast, some static_ If cast cannot complete the conversion, you can use … …
  • Most searched keywords: Whether you are looking for C++ static_cast,dynamic_cast,const_cast and reinterpret_cast (four types of conversion operators) reinterpret_cast can be consered as static_ A supplement to cast, some static_ If cast cannot complete the conversion, you can use … C++,Back-endC++ static_cast,dynamic_cast,const_cast and reinterpret_cast (four types of conversion operators) Implicit type conversion is safe and explicit type conversion is risky. The reason why C language adds the syntax of forced type conversion is to emphasize the risk and make programmers aware of whUTF-8…
  • Table of Contents:

static_cast keyword

const_cast keyword

reinterpret_cast keyword

dynamic_cast keyword

C++ static_cast,dynamic_cast,const_cast and reinterpret_cast (four types of conversion operators)
C++ static_cast,dynamic_cast,const_cast and reinterpret_cast (four types of conversion operators)

Read More


See more articles in the same category here: Chewathai27.com/to/blog.

When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used?

static_cast is the first cast you should attempt to use. It does things like implicit conversions between types (such as int to float , or pointer to void* ), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating static_cast isn’t necessary, but it’s important to note that the T(something) syntax is equivalent to (T)something and should be avoided (more on that later). A T(something, something_else) is safe, however, and guaranteed to call the constructor.

static_cast can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn’t cast through virtual inheritance. It does not do checking, however, and it is undefined behavior to static_cast down a hierarchy to a type that isn’t actually the type of the object.

const_cast can be used to remove or add const to a variable; no other C++ cast is capable of removing it (not even reinterpret_cast ). It is important to note that modifying a formerly const value is only undefined if the original variable is const ; if you use it to take the const off a reference to something that wasn’t declared with const , it is safe. This can be useful when overloading member functions based on const , for instance. It can also be used to add const to an object, such as to call a member function overload.

const_cast also works similarly on volatile , though that’s less common.

dynamic_cast is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The dynamic_cast will seek out the desired object and return it if possible. If it can’t, it will return nullptr in the case of a pointer, or throw std::bad_cast in the case of a reference.

dynamic_cast has some limitations, though. It doesn’t work if there are multiple objects of the same type in the inheritance hierarchy (the so-called ‘dreaded diamond’) and you aren’t using virtual inheritance. It also can only go through public inheritance – it will always fail to travel through protected or private inheritance. This is rarely an issue, however, as such forms of inheritance are rare.

reinterpret_cast is the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in an int , or all sorts of other nasty things. Largely, the only guarantee you get with reinterpret_cast is that normally if you cast the result back to the original type, you will get the exact same value (but not if the intermediate type is smaller than the original type). There are a number of conversions that reinterpret_cast cannot do, too. It’s used primarily for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data, or storing data in the low bits of a pointer to aligned data.

C-style cast and function-style cast are casts using (type)object or type(object) , respectively, and are functionally equivalent. They are defined as the first of the following which succeeds:

const_cast

static_cast (though ignoring access restrictions)

(though ignoring access restrictions) static_cast (see above), then const_cast

(see above), then reinterpret_cast

reinterpret_cast , then const_cast

It can therefore be used as a replacement for other casts in some instances, but can be extremely dangerous because of the ability to devolve into a reinterpret_cast , and the latter should be preferred when explicit casting is needed, unless you are sure static_cast will succeed or reinterpret_cast will fail. Even then, consider the longer, more explicit option.

C H A P T E R 9

C H A P T E R 9

Cast Operations

This chapter discusses the newer cast operators in the C++ standard: const_cast , reinterpret_cast , static_cast , and dynamic_cast . A cast converts an object or value from one type to another.

These cast operations provide finer control than previous cast operations. The dynamic_cast<> operator provides a way to check the actual type of a pointer to a polymorphic class. You can search with a text editor for all new-style casts (search for _cast ), whereas finding old-style casts required syntactic analysis.

Otherwise, the new casts all perform a subset of the casts allowed by the classic cast notation. For example, const_cast(v) could be written (int*)v . The new casts simply categorize the variety of operations available to express your intent more clearly and allow the compiler to provide better checking.

The cast operators are always enabled. They cannot be disabled.

The expression const_cast< T >( v ) can be used to change the const or volatile qualifiers of pointers or references. (Among new-style casts, only const_cast<> can remove const qualifiers.) T must be a pointer, reference, or pointer-to-member type.

class A { public: virtual void f(); int i; }; extern const volatile int* cvip; extern int* ip; void use_of_const_cast() { const A a1; const_cast(a1).f(); // remove const ip = const_cast (cvip); // remove const and volatile }

The expression reinterpret_cast< T >( v ) changes the interpretation of the value of the expression v. It can be used to convert between pointer and integer types, between unrelated pointer types, between pointer-to-member types, and between pointer-to-function types.

Usage of the reinterpret_cast operator can have undefined or implementation-dependent results. The following points describe the only ensured behavior:

A pointer to a data object or to a function (but not a pointer to member) can be converted to any integer type large enough to contain it. (Type long is always large enough to contain a pointer value on the architectures supported by the C++ compiler.) When converted back to the original type, the pointer value will compare equal to the original pointer.

is always large enough to contain a pointer value on the architectures supported by the C++ compiler.) When converted back to the original type, the pointer value will compare equal to the original pointer. A pointer to a (nonmember) function can be converted to a pointer to a different (nonmember) function type. If converted back to the original type, the pointer value will compare equal to the original pointer.

A pointer to an object can be converted to a pointer to a different object type, provided that the new type has alignment requirements no stricter than the original type. When converted back to the original type, the pointer value will compare equal to the original pointer.

An lvalue of type T1 can be converted to a type “reference to T2 ” if an expression of type “pointer to T1 ” can be converted to type “pointer to T2 ” with a reinterpret cast.

can be converted to a type “reference to ” if an expression of type “pointer to ” can be converted to type “pointer to ” with a reinterpret cast. An rvalue of type “pointer to member of X of type T1 ” can be explicitly converted to an rvalue of type “pointer to member of Y of type T2 ” if T1 and T2 are both function types or both object types.

” can be explicitly converted to an rvalue of type “pointer to member of Y of type ” if and are both function types or both object types. In all allowed cases, a null pointer of one type remains a null pointer when converted to a null pointer of a different type.

The reinterpret_cast operator cannot be used to cast away const ; use const_cast for that purpose.

operator cannot be used to cast away ; use for that purpose. The reinterpret_cast operator should not be used to convert between pointers to different classes that are in the same class hierarchy; use a static or dynamic cast for that purpose. ( reinterpret_cast does not perform the adjustments that might be needed.) This is illustrated in the following example:

class A {int a; public: A();}; class B: public A {int b, c;}; void use_of_reinterpret_cast() { A a1; long l = reinterpret_cast(&a1); A* ap = reinterpret_cast(l); // safe B* bp = reinterpret_cast(&a1); // unsafe const A a2; ap = reinterpret_cast(&a2); // error, const removed }

The expression static_cast< T >( v ) converts the value of the expression v to type T. It can be used for any type conversion that is allowed implicitly. In addition, any value can be cast to void , and any implicit conversion can be reversed if that cast would be legal as an old-style cast.

class B {…}; class C: public B {…}; enum E {first=1, second=2, third=3}; void use_of_static_cast(C* c1) { B* bp = c1; // implicit conversion C* c2 = static_cast(bp); // reverse implicit conversion int i = second; // implicit conversion E e = static_cast(i); // reverse implicit conversion }

The static_cast operator cannot be used to cast away const . You can use static_cast to cast “down” a hierarchy (from a base to a derived pointer or reference), but the conversion is not checked; the result might not be usable. A static_cast cannot be used to cast down from a virtual base class.

9.4 Dynamic Casts

A pointer (or reference) to a class can actually point (refer) to any class derived from that class. Occasionally, it may be desirable to obtain a pointer to the fully derived class, or to some other subobject of the complete object. The dynamic cast provides this facility.

Note – When compiling in compatibility mode ( -compat[=4] ), you must compile with -features=rtti if your program uses dynamic casts.

The dynamic type cast converts a pointer (or reference) to one class T1 into a pointer (reference) to another class T2. T1 and T2 must be part of the same hierarchy, the classes must be accessible (via public derivation), and the conversion must not be ambiguous. In addition, unless the conversion is from a derived class to one of its base classes, the smallest part of the hierarchy enclosing both T1 and T2 must be polymorphic (have at least one virtual function).

In the expression dynamic_cast< T >( v ) , v is the expression to be cast, and T is the type to which it should be cast. T must be a pointer or reference to a complete class type (one for which a definition is visible), or a pointer to cv void , where cv is an empty string, const , volatile , or const volatile .

9.4.1 Casting Up the Hierarchy

When casting up the hierarchy, if T points (or refers) to a base class of the type pointed (referred) to by v, the conversion is equivalent to static_cast< T >( v ) .

9.4.2 Casting to void*

If T is void* , the result is a pointer to the complete object. That is, v might point to one of the base classes of some complete object. In that case, the result of dynamic_cast( v ) is the same as if you converted v down the hierarchy to the type of the complete object (whatever that is) and then to void* .

When casting to void* , the hierarchy must be polymorphic (have virtual functions).

9.4.3 Casting Down or Across the Hierarchy

When casting down or across the hierarchy, the hierarchy must be polymorphic (have virtual functions). The result is checked at runtime.

The conversion from v to T is not always possible when casting down or across a hierarchy. For example, the attempted conversion might be ambiguous, T might be inaccessible, or v might not point (or refer) to an object of the necessary type. If the runtime check fails and T is a pointer type, the value of the cast expression is a null pointer of type T. If T is a reference type, nothing is returned (there are no null references in C++), and the standard exception std::bad_cast is thrown.

For example, this example of public derivation succeeds:

#include #include // for NULL class A {public: virtual void f();}; class B {public: virtual void g();}; class AB: public virtual A, public B {}; void simple_dynamic_casts() { AB ab; B* bp = &ab; // no casts needed A* ap = &ab; AB& abr = dynamic_cast(*bp); // succeeds ap = dynamic_cast(bp); assert(ap!= NULL); bp = dynamic_cast(ap); assert(bp!= NULL); ap = dynamic_cast(&abr); assert(ap!= NULL); bp = dynamic_cast(&abr); assert(bp!= NULL); }

whereas this example fails because base class B is inaccessible.

#include #include // for NULL #include class A {public: virtual void f() {}}; class B {public: virtual void g() {}}; class AB: public virtual A, private B {}; void attempted_casts() { AB ab; B* bp = (B*)&ab; // C-style cast needed to break protection A* ap = dynamic_cast(bp); // fails, B is inaccessible assert(ap == NULL); try { AB& abr = dynamic_cast(*bp); // fails, B is inaccessible } catch(const std::bad_cast&) { return; // failed reference cast caught here } assert(0); // should not get here }

In the presence of virtual inheritance and multiple inheritance of a single base class, the actual dynamic cast must be able to identify a unique match. If the match is not unique, the cast fails. For example, given the additional class definitions:

class AB_B: public AB, public B {}; class AB_B__AB: public AB_B, public AB {};

Example:

void complex_dynamic_casts() { AB_B__AB ab_b__ab; A*ap = &ab_b__ab; // okay: finds unique A statically AB*abp = dynamic_cast(ap); // fails: ambiguous assert(abp == NULL); // STATIC ERROR: AB_B* ab_bp = (AB_B*)ap; // not a dynamic cast AB_B*ab_bp = dynamic_cast(ap); // dynamic one is okay assert(ab_bp!= NULL); }

The null-pointer error return of dynamic_cast is useful as a condition between two bodies of code–one to handle the cast if the type guess is correct, and one if it is not.

void using_dynamic_cast(A* ap) { if (AB *abp = dynamic_cast(ap)) { // abp is non-null, // so ap was a pointer to an AB object // go ahead and use abp process_AB(abp);} else { // abp is null, // so ap was NOT a pointer to an AB object // do not use abp process_not_AB(ap); } }

In compatibility mode ( -compat[=4] ), if runtime type information has not been enabled with the -features=rtti compiler option, the compiler converts dynamic_cast to static_cast and issues a warning.

If exceptions have been disabled, the compiler converts dynamic_cast to static_cast and issues a warning. (A dynamic_cast to a reference type requires an exception to be thrown if the conversion is found at run time to be invalid.). For information about exceptions, see Chapter 8.

Dynamic cast is necessarily slower than an appropriate design pattern, such as conversion by virtual functions. See Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma (Addison-Wesley, 1994).

Copyright © 2005, Sun Microsystems, Inc. All Rights Reserved.

reinterpret_cast Operator

Table of contents

reinterpret_cast Operator

Article

08/03/2021

2 minutes to read

7 contributors

In this article

Allows any pointer to be converted into any other pointer type. Also allows any integral type to be converted into any pointer type and vice versa.

Syntax

reinterpret_cast < type-id > ( expression )

Remarks

Misuse of the reinterpret_cast operator can easily be unsafe. Unless the desired conversion is inherently low-level, you should use one of the other cast operators.

The reinterpret_cast operator can be used for conversions such as char* to int* , or One_class* to Unrelated_class* , which are inherently unsafe.

The result of a reinterpret_cast cannot safely be used for anything other than being cast back to its original type. Other uses are, at best, nonportable.

The reinterpret_cast operator cannot cast away the const , volatile , or __unaligned attributes. See const_cast Operator for information on removing these attributes.

The reinterpret_cast operator converts a null pointer value to the null pointer value of the destination type.

One practical use of reinterpret_cast is in a hash function, which maps a value to an index in such a way that two distinct values rarely end up with the same index.

#include using namespace std; // Returns a hash code based on an address unsigned short Hash( void *p ) { unsigned int val = reinterpret_cast( p ); return ( unsigned short )( val ^ (val >> 16)); } using namespace std; int main() { int a[20]; for ( int i = 0; i < 20; i++ ) cout << Hash( a + i ) << endl; } Output: 64641 64645 64889 64893 64881 64885 64873 64877 64865 64869 64857 64861 64849 64853 64841 64845 64833 64837 64825 64829 The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function. See also Casting Operators Keywords

So you have finished reading the static_cast reinterpret_cast topic article, if you find this article useful, please share it. Thank you very much. See more: Reinterpret_cast vs static_cast, Dynamic_pointer_cast, Difference between static_cast and reinterpret_cast in c++, Reinterpret_cast C++, Static_cast in C++, Dynamic_cast, Static_cast to void, C style cast

Leave a Comment