Hi :)

I am certain of when to use static_cast, but often I can get satisfactory results by writing the target type in a parenthesis.

For example:

void* data = somePointer;
SomeClass* new_ptr = static_cast<SomeClass*>(data);

seems to work when replaced with

void* data = somePointer;
SomeClass* new_ptr = (SomeClass*) data;

So could anyone help me out, what the difference in the methods are? :)

Thank you.

According to the book "Thinking in C++" the second example is the "old" way of doing things while static_cast<> is the "new" way. So, the old way would be the kind of code you'd see in C while the static cast would be the C++ way of doing things. (From pg 169)

The static_cast<> lets the c++ compiler do a better job of ensuring the cast is valid. For example: this will produce a compiler error (vc++ 2008 express)

int  main()
{
    int x = 123;
    char* p = static_cast<char*>(&x);  // << ERROR
    char* p = (char*)&x;  // << NO ERROR
}

Thank you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.