In article <d5ce22d0-225b-42e4-8d6c-
>,
says...
[ ... ]
> 1. What is the purpose of C++'s static_cast<>? In other words, is
> there any real difference between statements like (with non-pointer
> types):
>
> double a = 3.4;
> int b = (int)a; // <--- this
> int c = static_cast<int>(a); // <---
There is no difference between these statements. For that matter,
int c = 3.4;
is allowed, and does exactly the same thing as well.
The reason for static_cast over a C-style cast is mostly that it is more
restricted, and does NOT support some more dangerous conversions that C-
style casts can do. For example, a C-style cast can do roughly the same
thing as a const_cast, casting away const-ness, or it can do roughly the
same thing as a reinterpret_cast, treating a pointer as if it pointed to
a different type of operand.
> 2. What about static cast with void*'s and pointers to class types, is
> there any difference here, and also, are these conversions all safe:
>
> Object *a = new Object;
> void *b = a;
> Object *c = (Object *)b;
> Object *d = static_cast<Object *>(b);
>
> In that code is there any difference between the conversion when
> initializing c and d? And, are c/d guaranteed to be valid pointers to
> the same object a points to?
Yes, the conversions to c and d are the same. A C-style cast does the
same thing as a static_cast when/if a static_cast can do the conversion.
A static_cast can't do anything new that a C-style cast can't. The
advantage of a static_cast is solely that it is more restricted, so you
can't, for one example, accidentally cast away const-ness and/or
reinterpret what a pointer points at -- for example:
int const *a;
char *b = (char *)a; // perfectly legal
char *b = static_cast<char *>(a); // not allowed
The C-style cast is casting away the const-ness AND reintrepting what's
pointed at as a char instead of an int. A static_cast simply can't do
that -- if you really want to cast away const-ness, you need to use
const_cast. If you want to reinterpret what's pointed at, you have to
use reinterpret_cast. If you want to do both, you have to use both:
char *c = const_cast<char *>(reinterpret_cast<char const *>(a));
The C-style cast can do so many different kinds of conversions, with
nothing to distinguish between them, that it's easy to accidentally do a
conversion you don't want along with the one(s) you did. The new-style
casts attempt to prevent that.
--
Later,
Jerry.
The universe is a figment of its own imagination.