Re: Question regarding cast
On Thursday, 20 June 2013 04:22:00 UTC+1, Nobody wrote:
On Wed, 19 Jun 2013 23:05:21 +0000, Jorgen Grahn wrote:
As I understand this thread, none of this is a problem unless you override
the type system using reinterpret_cast<T> or something even worse. And
few people ever have to do that, to types like these, anyway.
This is an issue for interfacing C++ code to C, or to other languages
which have mechanisms for interfacing with C.
Since C doesn't have derived classes, I don't see how this can
be an issue. Classes which can be exported to C can't be
derived classes.
Consider:
class SomeClass {...};
// C API
extern "C" {
void *new_object() { return static_cast<void*>(new SomeClass()); }
void free_object(void *obj) { delete static_cast<SomeClass*>(obj); }
void object_foo(void *obj) { static_cast<SomeClass*>(obj)->foo(); }
void object_bar(void *obj) { static_cast<SomeClass*>(obj)->bar(); }
// ... and so on
}
If you try to export the "an instance of a derived class is also an
instance of a base class" semantics to C, you'll get bitten by multiple
inheritance. You have to convert to the appropriate base class before
passing the pointer off to C code.
Obviously.
IMO it's a parallel to the endless
endianness/padding/alignment etc discussions. You can spend
a lifetime fighting that stuff ... but it's a non-issue
unless you break the type system. Willingly and on purpose.
Again, this can be necessary if you have to interface to the outside
world, particularly if efficiency is a consideration.
Again, it's not an issue *if* you respect the type system. One
of the rules of the types system is that to use a pointer
converted to void*, you have to convert it back to its original
type. Anything else is undefined behavior.
--
James