User forums > General (but related to Code::Blocks)

cast and static cast

<< < (2/4) > >>

takeshimiya:

--- Quote from: Urxae on December 09, 2005, 04:49:28 pm ---Sorry, not true.

--- Code: ---class A {};
class B {};

int main()
{
    A a;
    B b;
    A* pa = &a;
    B* pb1 = (B*) pa;               // allowed, but don't do this
    B* pb2 = static_cast<B*>(pa);   // not allowed
}

--- End code ---

--- End quote ---

Sorry, I was trying to mean
(type)(variable)  C way
static_cast<type>(variable)  C++ way

Urxae:

--- Quote from: Takeshi Miya on December 09, 2005, 05:52:45 pm ---Sorry, I was trying to mean
(type)(variable)  C way
static_cast<type>(variable)  C++ way

--- End quote ---

But you claimed they were the same, which wasn't true. They're similar, but static_cast<> is safer.

rickg22:
:-o

OK, thanks :) I guess that answers my question.

takeshimiya:

--- Quote from: Urxae on December 09, 2005, 08:44:58 pm ---But you claimed they were the same, which wasn't true. They're similar, but static_cast<> is safer.

--- End quote ---

Thanks, I didn't know that it was safer in that sense, I thought that it was safer for academic reasons. :P

me22:
The nicest example I've seen is switching implementation styles.

You initially used Employee* as your handle type, but you change it to unsigned ints for some reason.  The compiler catches most of the changes, but you have one hidden issue:

--- Code: ---void Employee::setManager(handle new_manager) {
    manager_.removeSubordinate( this );
    manager_ =  (Manager*)new_manager;
    manager_.addSubordinate( this );
}
--- End code ---
Now this is bad code on multipule levels ( not exception safe, for example ) but that cast is evil.  The compiler will not longer care that the cast has changed from a fairly acceptable, though unsafe, downcast to a completely meaningless integer reinterpretation.

Note that in C++, c-style casts are actually defined in terms of a complex sequence of the named casts.

static_cast : innocent casts.  Derived* to Base*, int to float, etc
const_cast : adding or removing const -- no other named casts allow this, which is a good thing
dynamic_cast : checked Base* to Derived*
reinterpret_cast : to be avoided.  Only useful for passing T* as the data argument of a C callbacks, since any use other than casting T* to U* and back to T* is undefined or implementation-defined.

Here's another instructive demo:

--- Code: ---#include <iostream>

struct B { char c; };
struct D : B { char a; };

int main() {
    D d;
    std::cout << &d << std::endl;
    std::cout << (B*)&d << std::endl;
    std::cout << static_cast<B*>(&d) << std::endl;
    std::cout << reinterpret_cast<B*>(&d) << std::endl;
    std::cout << (void*)&d << std::endl;
    std::cout << static_cast<void*>(&d) << std::endl;
    std::cout << reinterpret_cast<void*>(&d) << std::endl;
}
--- End code ---

Navigation

[0] Message Index

[#] Next page

[*] Previous page

Go to full version