-3

In C++, it is well known that when trying to access a data-member or a function inside of an object, you put the object name followed by a dot, then whatever you want to access. But if the type is a pointer, then instead of a dot you use an arrow, which is "->". I know this, but what I want to know is why the creators of C++ made it this way.

Example:

random_object o;
o.random_field;

However with pointers:

random_object* o = new random_object();
o->random_field;
nexus
  • 94
  • 8
  • 2
    Because C did it that way. And you don't *have* to, you could also write `(*o).random_field`, it's just less convenient – UnholySheep Oct 14 '19 at 22:28
  • If its because C did it that way, why did C do it that way? – nexus Oct 14 '19 at 22:30
  • 3
    See: https://stackoverflow.com/questions/13366083/why-does-the-arrow-operator-in-c-exist – UnholySheep Oct 14 '19 at 22:32
  • Not only can you alternatively write `(*o).random_field`, you could also write `o[0].random_field` or even `0[o].random_field` ... that's from C. C was influenced from B programming language, but it is hard to find much information about B these days. – Eljay Oct 15 '19 at 02:44

1 Answers1

3

The . operator is how you access members given (a reference to) an instance of an object. It accesses a member at a given offset from the beginning of the object.

The -> operator is a cleaner shorthand when you have a pointer to an object. It dereferences the pointer for you, and then applies the offset, all in one operation. Otherwise, you would have to dereference the pointer manually.

In other words, o->random_field; is the exact same as (*o).random_field; when o is an object pointer.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770