purpose of ->

why do i have to use -> in pointers instead of dot(.)
Why have they created a different symbol?
From the point of view of language design, there's no real reason why the arrow operator needed to exist.

From the point of view of compiler design, since C first appeared in the early 70's my guess would be that the designers noticed that compilation could go faster if they relied on the programmer to use the right operator in the right context, rather than having the compiler figuring out what to do. Remember that C was designed for the PDP-11, a machine with less than 8K of memory.
> why do i have to use -> in pointers instead of dot(.)
> Why have they created a different symbol?

The reasons are historical; but if the -> operator was not there, C++ would have had to invent an overloadable indirection operator anyway (RAII).
But you can use a dot:

1
2
3
4
5
6
7
8
9
10
struct MyStruct
{
  int intValue;
}

MyStruct aStruct;

MyStruct* aPtr = &aStruct;

std::cout << "My structure contains the value " << (*aPtr).intValue;


aPtr->intValue is just syntactical sugar for (*aPtr).intValue.

A pointer doesn't have members. A pointer is just a number.
Last edited on
> But you can use a dot: etc.
> syntactic sugar etc.

Repeat: if the -> operator was not there, C++ would have had to invent an overloadable indirection operator anyway (RAII).

That is not as hard to understand as it may appear at first sight. Think about std::vector<bool>, think about smart pointers (and iterators).
The old historical reason for -> in C (not C++) is actually pretty fascinating, I saw it documented on SO here: https://stackoverflow.com/a/13366168

(in short, in pre-K&R C, -> did not require a pointer on the left, and you could write things like "100->a = 0;" to write zero at address 100 plus the offset of a (a had to be a struct member, all struct members were globally visible, like enumerators). K&R 1st edition imposed the pointer requirement and made A->B same as (*A).B)
Last edited on
Repeat: if the -> operator was not there, C++ would have had to invent an overloadable indirection operator anyway (RAII).

Fair point - and, yes, the smart pointer example did occur to me after I hit Submit.

I suspect they could have done something clever with overriding the dereference operator, maybe? But having a separate operator is more elegant.
@Mikeyboy your answer solved an unrelated problem of mine lol.

http://www.cplusplus.com/forum/beginner/223192/
Huh... OK. I actually just posted a reply to that thread, before I saw this.

Do you actually understand what a pointer is?
yes
Registered users can post here. Sign in or register to post.