The important thing is
type.
Type allows the compiler to check that you're using a given bit pattern in the correct way.
The cast in C/C++ allows you to override the type system and take manual control of the use of specific bit patterns. But then the problem of checking that you're doing the right thing becomes your own.
The rules around override are complicated because they must be done in a platform independent way. For example the 68000 series processor does not allow a pointer to a signed integral value to be used on an unsigned equivalent, so the standard has to accomodate that sort of thing.
Is it ok to use a void* to store the address of a class? |
As Duoas said, no it's not. Because you loose the type information, the compiler cannot help you dereference that pointer correctly.
But isn't null the absolute pointer 0x0? |
No. Zero is just a value. It's not a type. It's used with pointers to indicate the pointer doesn't point anywhere (that interpretation is what we call type).
1 2 3 4
|
A a = {5};
B* b = reinterpret_cast<B*>(&a);
b->i = 500;
cout << a.i << endl;
|
This code is an example of a programmer bypassing the type system. The compiler can only syntax check that:
1. A can be initialised with 5.
2. A and B have member's called i, but it doesn't check that they're at the same offset within the struct/class.
If A was defined as:
1 2 3 4
|
struct A
{
int a, b, c, d, e, f, g, h, i;
};
|
and B was defined as:
1 2 3 4
|
struct B
{
int i;
};
|
a.i and b->i would not refer to the same bit pattern and the compiler couldn't help as you overrode the type system.
Without type, we may as well be using B or Smalltalk and discover our type errors at runtime.