Does C++ enforce this only because it makes code more readable?
If you want statements like ptr->field to make any sense to the compiler, it needs to know what pointers point to.
You don't have to declare the type of object a pointer points to. This is what the pointer-to-void (void *) type is -- a pointer to an object of an unknown type.
Of course, if you don't know the type of object then you cannot do anything useful with it, which is why C++ doesn't let you do much with a pointer-to-void except use it where a pointer-to-void is expected, or cast it to another pointer type.
You can also point to an incomplete type:
class Something;
Something * somethingPtr = nullptr;
Now we have a pointer to an object of type Something, but we don't know anything about that type and so we can't perform any operations on the target object:
// error: invalid use of incomplete type ‘class Something’
somethingPtr->foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With