1

Possible Duplicate:
Why does C have a distinction between -> and .?

Compilers are smart enough to know if the left side operand is a pointer or a reference. Why are there two different operators (. and ->) for member access?

Is it to make the indirection explicit? For legibility? Was there something about the available hardware when C was designed that made a strong case for those operations to be easily distinguished when reading source code?

I've read about it simply being a shorthand syntax for (*ptr).member, but is ptr.member ever valid when ptr is a pointer? Why can't ptr.member "just work" as ptr->member if ptr is a pointer?

Community
  • 1
  • 1
Reuben Morais
  • 1,013
  • 1
  • 8
  • 20
  • Yes, exact duplicate. I should have searched more. – Reuben Morais Dec 18 '12 at 02:03
  • 1
    a) "Why can't ptr.member "just work" as ptr->member if ptr is a pointer?" it could, in C, but doesn't for historical reasons. b) In C++ it would be an incompatible change due to operator overloading. c) Note that function pointers are automatically dereferenced ... `p()` is equivalent to `(********p)()` d) Use a more modern language like rust or D. – Jim Balter Dec 18 '12 at 06:47

1 Answers1

1

Not quite an answer, but one place this distinction is taken advantage of is with smart pointers and container iterators.

In both cases, the . operator is used to operate on the object itself, while the -> is used to operate on the object that is contained within.

Karthik T
  • 31,456
  • 5
  • 68
  • 87