Shane
Shane

Reputation: 103

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

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

Upvotes: 2

Views: 115

Answers (5)

Chris Drew
Chris Drew

Reputation: 15334

It makes code more readable but more importantly it makes code much safer.

You could imagine some syntax (like void*) where you have to tell it the type whenever you want to dereference or delete a pointer but that would make for unsafe, unreadable code.

Upvotes: 0

cdhowie
cdhowie

Reputation: 168988

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();

Upvotes: 7

rcgldr
rcgldr

Reputation: 28828

Or take the case of somePtr[i] or *(somePtr[i]), where i is multiplied by the object size in bytes, or somePtr++, where somePtr is effectively incremented by the object size.

Upvotes: 1

zneak
zneak

Reputation: 138031

If you had:

struct foo
{
    int bar;
    int baz;
};

foo* myFoo = new foo;

How would you do myFoo->bar if you couldn't even tell that myFoo has a bar field?

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

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

Upvotes: 8

Related Questions