tags:

views:

223

answers:

3

Is there anything like C++s safe casts in Objective-C?

I know that they are in Objective C++, but I am unsure about possible side effects. Using Objective C++ may slow compilation time - are there any other reasons not to use it?

A: 

Which feature of C++ do you think will help you cast a 64-bit long to a 32-bit int?

Darren
In many compiler implementations `long` is 32-bit even on 64-bit target. And `long long` is 64-bit.
KennyTM
Not in unix or OS X. The compiler should give you a good warning about that.
Darren
This should have been a comment - not an answer. The casting was a mistake - I believe that I would have received a warning if I was using a C++ cast
Casebash
You will get a warning when you try to assign a 64-bit long to a 32-bit int. You use a static cast precisely to get rid of that warning. By using a static cast you're telling the compiler that you know what you're doing. Whether you use a plain old C cast or a c++ static_cast the result is the same.
Darren
I wasn't getting a warning
Casebash
Anyway, even if the motivation for asking about safe casts is incorrect, the question is still one I'd like to answer
Casebash
A: 

You can turn on compiler flags to warn you in cases like this. This particular mistake would be caught by the -Wconversion flag.

Chuck
-Wconversion seems to miss the error and raise a lot of spurious errors instead
Casebash
+1  A: 

Objective-c does have C++ safe casts. Alternatively, we can use runtime reflection:

id myOb=[someObject getObject];
NSAssert([myOb isKindOfClass:[MyClass class]], @"Return value is not of type MyClass as expected.");
MyClass * newOb= (MyClass *)myOb;

References:

Cocoa with Love:

Casebash