Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If pointers are all the same size, how come we have to declare the type of object they point to?

Tags:

c++

pointers

Does C++ enforce this only because it makes code more readable?

like image 533
Shane Avatar asked Dec 05 '25 13:12

Shane


2 Answers

If you want statements like ptr->field to make any sense to the compiler, it needs to know what pointers point to.

like image 177
Scott Hunter Avatar answered Dec 07 '25 02:12

Scott Hunter


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();
like image 27
cdhowie Avatar answered Dec 07 '25 02:12

cdhowie