Sei sulla pagina 1di 5

Ask or Search Quora

C++ (programming language)

Ask Question

Learning to Program

How-to Question

Why are they really needed?

Request Answers

Follow 28

Comment Share 1

Answer

Notifications

Suman

+3

How do you explain the differences among static_cast,


reinterpret_cast, const_cast, and dynamic_cast to a new
C++ programmer?
Write Answer

Read

Downvote

There's more on Quora...

Pick new people and topics to follow and see the


best answers on Quora.
Update Your Interests

Question Overview

5 Answers
Brian Bi, software engineer

11.5k Views Upvoted by Sergey Zubkov, C++ programmer (using boost and C++14) Vivek
Nagarajan, Writing C++ since 2003 Dima Korolev, Used to teach C++.
Brian is a Most Viewed Writer in Learning to Program.

Why are they really needed?


Good question! Actually, this is the key to understanding why C++ has four different casts.

28 Followers

13,789 Views
View More

Related Questions

In C there is only a single cast, but it performs many different conversions:


1. Between two arithmetic types
2. Between a pointer type and an integer type
3. Between two pointer types
4. Between a cv-qualified and cv-unqualified type
5. A combination of (4) and either (1), (2), or (3)

Why isn't the reinterpret_cast safe on C++?

C++ adds the following features that really change the game:
Inheritance
Templates

How is <dynamic_cast> implemented in C++03?

Why are these important? Well, inheritance changes the game because now there are three
different things we might mean by a pointer cast. Say class D derives from class B. What
should (D*)pb do, where pb has type B*? Here are three possibilities:
1. Return a pointer to the same byte of memory, but just change the type of the
pointer. (This is the same as what all pointer casts do in C, as explained above.)
2. Check whether the B* really points to a B that is part of a D object. If so, return a
pointer to the D object. If not, fail (maybe by returning a null pointer or throwing
an exception.)
3. Assume that the B* points to a B that is part of a D object; don't bother
performing a check. Adjust the address of the pointer if necessary so that it will
point to the D object.
It is conceivable that in C++ we might want to perform any of these three conversions.
Therefore C++ gives us three different casts:reinterpret_cast<D*> for function (1),
dynamic_cast<D*> for function (2), and static_cast<D*> for function (3).

Now, I also mentioned the fact that C++ has templates. The reason why this is relevant is
that if you use C-style casts in C++, and either the source or target or both types are
template parameters or depend on template parameters, then in general the kind of
casting involved might depend on the template parameters. For example, say we write a
function like this:
template <class T>
unsigned char* alias(T& x) {
return (unsigned char*)(&x);
}
So you can pass in any lvalue and you get a pointer to its first byte. All right! But hang on,
what happens if I pass in a const lvalue? Then the C-style cast silently casts away the
constness, and the function returns an unsigned char* which we can then use to
modify the original object, causing undefined behaviour. So, you see, the C-style cast to
pointer sometimes just changes the type of the object pointed to, but sometimes it just
removes const (like if we pass in a const unsigned char lvalue) and sometimes it does
both (like if we pass in a const int lvalue). Better to write
template <class T>
unsigned char* safe_alias(T& x) {
return reinterpret_cast<unsigned char*>(&x);

What are the disadvantages of C style casting in C++?


What are the technical reasons why I cannot
downcast (static_cast) in C++ when in the class
hierarchy exists one virtual i...

Why are dynamic casts generally frowned upon in


C++?
Why should I always use static_cast operator instead
of C style casts & function style cast?
How do we use const type casting to avoid method
overloading in C++?
What is type casting in C++?
Explain static and dynamic casting (c++) in layman
terms?
What is type casting in C? What are some examples?
More Related Questions

Ask or Search Quora

Ask Question

That way, if someone passes in a const lvalue, they'll get a compilation error, telling them--whoops! You almost casted away constness, which is super dangerous! Glad we caught
that in time, eh?
And that's why we need const_cast as a separate cast from the other three casts: its
function is entirely distinct from the other three casts' functions, you rarely need to cast
away constness, and you almost always want the compiler to prevent you from accidentally
casting away constness. If every static_cast, dynamic_cast, and
reinterpret_cast had the power to cast away constness too, using them would become
a lot more dangerous---especially when templates are involved! Now if someone really
wants to get a char* to a const int object, they can call, e.g.,
safe_alias(const_cast<int&>(x)). Now it's explicit that constness is being cast
away.
The fact that C++ has templates also forces us to explicitly perform implicit conversions
sometimes! Consider the following in C:
int* pi;
void* pv = pi; // OK; implicit conversion
void* pv2 = (void*)pi; // OK but unnecessary
void f(void* pv);
f(pi); // OK; implicit conversion
f((void*)pi); // OK but unnecessary
But in C++ we can have something like this:
template <class T> void f(T* p);
// ...
int* pi;
f(pi); // OK; calls f<int>
f(static_cast<void*>(pi)); // OK; calls f<void>
Even though int* can be converted to void* without a cast, we might still need a cast
anyway in order to force the argument to have the correct type! (That is, if we want to call
f<void> and not f<int>.) In C this doesn't happen because you can't overload functions,
let alone write function templates.
Boost provides an implicit_cast function template specifically designed to explicitly
perform implicit conversions. Many people feel that this should become a part of standard
C++. But for now all we have is static_cast. So to summarize approximately:
static_cast performs implicit conversions, the reverses of implicit standard
conversions, and (possibly unsafe) base to derived conversions.
reinterpret_cast converts one pointer to another without changing the
address, or converts between pointers and their numerical (integer) values.
const_cast only changes cv-qualification; all other casts cannot cast away
constness.
dynamic_cast casts up and down class hierarchies only, always checking that
the conversion requested is valid.
and the reason why there are four different casts in C++ is so that you can write a cast and
be explicit about what kind of conversion you intend to perform; the compiler will never
incorrectly "guess" what you meant; and other people reading your code will be able to tell
what kind of conversions it does.
Written Aug 24, 2014 View Upvotes
Upvote 174

Downvote Comments 5+

Share 8

Joe Wezorek, Wrote pro C++ from the 1990s to mid-2000s, now I work mostly in
C# and python
1.8k Views Joe has 320+ answers in Computer Programming.

Originally Answered: Why are there different types of cast in C++?

The different casts are there to indicate the intent of the cast. They say different things
about what you are doing.
Briefly a const_cast says "I am writing this code to be const correct but please excuse this
one little place where I need to cheat for reasons of expedience or because the 3rd party
code I am dealing with here ignores the notion of const-ness entirely"

Read

Answer

Notifications

Suman

static_cast says either "Dear C++, please perform this bit of type coercion which I am
Ask
or Search
indicating that you
know
how toQuora
perform, a valid conversion is part of you, Ask
the Question
language"
or "I have provided a constructor that makes this cast well-defined, please use it" or it says
"I am downcasting but I, the programmer, am guaranteeing to you C++ this is valid here.
I've looked at all the ways this cast can happen here and it will always be the case that it is
a valid downcast."
dynamic_cast says "I am downcasting but actually I am not sure on this one. C++ can you
check that this okay when you get here? If this cast isn't valid, just null out the pointer."
reinterpret_cast says "Trust me, I know what I am doing. This looks totally wrong but it
isn't. Just take these here bytes that you think are an X and treat them like a Y. It will be
fine."
A C-style cast can do everything the above can do -- and more -- but it does not indicate
intent and leads to unclear code.
I think the thing that beginners don't get is that a lot of what gets declared in serious
languages like C++ is not for them, the author of the code. C++ is about code that will be in
production, code that will be around for years.
In this case, the fact that there are different kinds of casts instead of one big dumb C cast is
mostly for the benefit of people who will be reading the code months or years later when
the author may be long gone. For those people it is very nice when the code is telling them
"Hey, the only reason this cast is here is to muck around with const-ness, so don't worry
too much about this cast." and so forth.
Written Nov 21, 2014 View Upvotes
Upvote 10

Downvote Comments 1+

Share

Dinesh Khandelwal, Computer Science Undergraduate

1.2k Views Dinesh has 50+ answers and 8 endorsements in C++ (programming language).

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 pointers and references up
the hierarchy.
static_cast performs no run-time checks.
int a = 5, b = 2;
double result = static_cast<double>(a) /

b;

dynamic_cast

It can only be used with pointers and references to objects. It's almost exclusively used for
handling polymorphism. It makes sure that the result of the type conversion is valid and
complete object of the requested class.
class Base { };
class Derived : public Base { };
Base a, *ptr_a;
Derived b, *ptr_b;
ptr_a = dynamic_cast<Base *>(&b); // Fine
ptr_b = dynamic_cast<Derived *>(&a); // Fail
The first dynamic_cast statement will work because we cast from derived class to base.
The second dynamic_cast statement will produce a compilation error because base class
to derived conversion is not allowed with dynamic_cast unless the base class is
polymorphic (a polymorphic type has at least one virtual function, declared or
inherited).
If a class is polymorphic then dynamic_cast will perform a special check during

Read

Answer

Notifications

Suman

execution.

Ask or Search Quora

Ask Question

class Base { virtual void dummy() {} };


class Derived : public Base { int a; };
Base *ptr_a = new Derived;
Base *ptr_b = new Base;
Derived *ptr_c, *ptr_d;
ptr_c = dynamic_cast<Derived *>(ptr_a);
ptr_d = dynamic_cast<Derived *>(ptr_b);

// Fine
// Fail

The pointer ptr_a points to an object of the type Derived. The pointer ptr_b points to
an object of the type Base. So when the dynamic_cast is performed then ptr_a is
pointing to a full object of class Derived, but the pointer ptr_b points to an object of
class Base. This object is an incomplete object of class Derived; thus this cast will fail !
A null pointer is returned to indicate a failure while dealing with a pointer. When
a reference type conversion fails then there will be an exception thrown out
instead of the null pointer.
dynamic_cast can cast pointers of any type to void *.

reinterpret_cast

It is used for casts that are not safe and it is dangerous:


Between pointers and pointers (even of unrelated classes). All pointer
conversions are allowed: neither the content pointed nor the pointer type itself is
checked.
Between integers and pointers.
Between function-pointers and function-pointer
However it can't modify const qualification.
class A { /* ... */ };
class B { /* ... */ };
A *a = new A;
B *b = reinterpret_cast<B*>(a);

// Fine

char *const cptr = 0;


int *iptr = reinterpret_cast<int *>(cptr);

// Fail

const_cast

The only way to cast away the const properties of an object is to use const_cast.
The use of const_cast on an object doesn't guarantee that the object can be used (after
the const is cast away.) Because it is possible that the const-objects are put in read-only
memory by the program.
The const_cast can not be used to cast to other data-types, as it is possible with the
other cast functions.
int *a;
const char *ptr = "Hello";
a = const_cast<int *>(ptr); // Fail
a = reinterpret_cast<const char*>(ptr); // Fail
a = reinterpret_cast<int *>(const_cast<char *>(ptr)); // Fine
Updated Jul 27 View Upvotes
Upvote 17

Downvote Comment Share 1

Read

Answer

Notifications

Suman

David Godfrey,
Web Development
enthusiast.
Ask or Search
Quora
1.3k Views

Ask Question

This post answers the question very well: When should static_cast, dynamic_cast,
const_cast and reinterpret_cast be used?
Written Aug 24, 2014 View Upvotes
Upvote

Downvote Comment Share

Afzaal Ahmad Zeeshan, beginner in programming with 5 years of experience


544 Views

Originally Answered: Why are there different types of cast in C++?

Type casting is needed when you need to use a variable of different data type in a context
where some other data type is required.
There are two types of castings, implicit and explicit type casting. Implicit can be done by
the compiler and explicit is done by developer, like this
double d = 0.0;
int i = (int) d; // would have value 0 now

MSDN documentation for Casting Operators


Read it.
Written Nov 21, 2014
Upvote

Downvote Comments 1+

Top Stories from Your Feed

Share 1

contains a good resource on this topic.

Read

Answer

Notifications

Suman

Potrebbero piacerti anche