C++ type casting

I have been using PHP (and a few other languages) for close to 7 years. I have a pretty deep understanding of casting, and how it works in those languages...all though to be honest, I rarely if ever need it.

That makes me wonder about C++. I see there are two ways to perform casting..the C style short casting..and the C++ functions to perform casting. After reading 2-3 books and doing some searches it seems the short way is generally discourages.

So focusing on the C++ style casts..I was able to narrow it down to 4 core things I needed to look at for casting..
Dynamic, Static, Reinterpet, and constant.

After all of the reading I have done in books, and via: http://www.cplusplus.com/doc/tutorial/typecasting/
the casting is only making a little sense, if any.
Basically each function has a specific purpose that it's used for...let's start with the first...

Dynamic: I have NO idea what this does..I can't understand any of this one.
Static:

well..none of them make sense..all that I have read in that tutorial and in the books makes absolutely no sense. My understanding of casting in related to programming should simply mean..change a variable from one type of data to another.....
Meaning...convert an int to a string..convert a string to an int..convert a constant into a int.....In my thinking..there is no way you can convert an object to a string or an object to an int...these 4 different uses for doing casting is not making any sense...I was expecting something like:
function to convert from string to int and vice versa as well as some others for perhaps other data types.

Any one have an english explanation of this..I am a good programmer with those other languages..but in C++ I haven't even gotten to classes a lot (not as much as I have in PHP, and I don't even know really what a pointer is..or how (in theory) it works.
I myself have the same problem with understand the differences, I kinda get it however when it comes to using them myself I ALWAYS have to refer to tutorials before I do to make sure I'm using the correct one in the correct scenario

Except in the case of say casting a double to an int. This method I use a lot dealing with numbers, and I think typically static casting is fine.

1
2
3
int a;
double b=5234.6345;
a static_cast<int>(b);


I'm also curious if someone can explain it better than the current tutorial does.
Last edited on
If I'm not mistaken:
dynamic_cast: converts a [pointer to a base class] to a [pointer to a derived class] at run time. For example, we have classes A, B, and C, A being the base and B and C deriving from A. If you dynamic_cast a A * to a B *, when the object being pointed to wasn't a B, the cast will throw and exception that can be caught.
static_cast: same as dynamic_cast, but no run time checks are performed.
const_cast: allows casting from const T * to T * and vice versa. No other casts are allowed.
reinterpret_cast: convert anything to anything without restrictions. Exactly the same as a C cast.
Last edited on
OK some of that makes sense.
I understand reinterpret cast is used to just change something to something else..regardless.

Constant..simple changes a constant to not a constant and vice versa.

I am still totally lost on the first two. Dynamic, and statis. Maybe it's because i dont know what a pointer is.
Don't worry. You won't need them until you learn about inheritance and polymorphism.
reinterpret_cast: convert anything to anything without restrictions. Exactly the same as a C cast.

Corrected:

C style casts are probably closer to static_cast.

reinterpret_cast is a binary reinterpretation of the data (no context/brains involved... just a straight binary copy). There are also plenty of restrictions on what you can reinterpret_cast. You can't reinterpret a float to an int, for example.

static_cast (and most C casts) examine context and intelligently modify binary data where necessary.

C style casting is like an unholy combination of static_cast and reinterpret_cast (and I guess const_cast since they can modify the const identifier). Sometimes you get one, sometimes you get the other. It depends on the situation.

EDIT:

Anyway, businessman:

When in doubt, use static_cast.

Use dynamic_cast when downcasting pointers (casting from a parent class pointer to a child class pointer). If you are 100% sure of the type you can use static_cast here too, but be very sure

const_cast and reinterpret_cast are very very seldomly used.

Last edited on
Well, this is the most useless shit ever. It doesn't even let me convert between differently-signed versions of the same type. What the hell is reinterpret_cast good for?

Ugh. Just leave me with my C casts.
Last edited on
What the hell is reinterpret_cast good for?


Very little.

1) You can convert between objects of unrelated pointer types (cast from A* to B* if A and B are unrelated -- which you can't do with static_cast)

2) You can sidestep automatic pointer correction in instances of casting where multiple inheritance is involved:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

class ParentA   {  int a;   };
class ParentB   {  int b;   };
class Child : public ParentA, public ParentB {  int c;  };

int main()
{
    Child c;
    std::cout << &c << "\n";

    // compare these two
    std::cout << static_cast<ParentA*>(&c) << "\n";
    std::cout << static_cast<ParentB*>(&c) << "\n"; // *

    // to these two
    std::cout << reinterpret_cast<ParentA*>(&c) << "\n";
    std::cout << reinterpret_cast<ParentB*>(&c) << "\n";

    // on my compiler the * cast is 4 bytes greater than all others

    return 0;
}


WHY you'd ever want to do that is something of a mystery. I do it when converting to/from void pointers just so I can be sure nothing is getting switched on me (though I'm sure it's not necessary)
One further correction.

dynamic_cast, when used on pointers, returns NULL if the downcast cannot be performed. When used on references,
it will throw in the error case.
One way to think of it is:
reinterpret_cast is used to look at an existing value in a different way without changing it.

static_cast is used to convert one type to another using language defined rules. This may change the underlying value.
e.g.
1
2
int i = 7;
double d = i;  // static cast implied here 


const_cast is easy. It casts away const/volatile.

dynamic_cast has been explained above, it's a typesafe down cast determined at runtime.


Why bother with four kinds of cast?
In C, you cast all the time. With the C style cast, you're not always sure what you've asked the compiler to do (was it const, reinterpret or static?) and can be a source of error.

In C++, there are far fewer casts. And if you do in fact cast, you should be clear on why you're casting, both for your own sanity check and for the benefit of people who come along and read your code later. Remember, the purpose of the cast is to subvert the compiler's type checks. The C++ cast gives you an extra level of protection from yourself.
Last edited on
Perfect, thanks guys. That really put a lot of things into perspective. Now I learned what pointers were (which I am about to ask a question about) and that makes this come together a lot better.
Topic archived. No new replies allowed.