C++Syntax: Member selection: -> .


This syntax is used to select a data member or a member function given a pointer to an object (->) or an object (.) Selecting a data member means getting direct access to a members data, at most objects won't allow that as it breaks the hiding (or encapsulation) of its data. Selecting a member function means calling that function (i.e. passing the object a message).

To pass a message to an object given a pointer to it requires the -> operator:-

The operation involves two steps:-
  1. The pointer is followed to get to the object. This is called dereferencing The syntax is:- *objptr
  2. The member function is selected. This step can also be performed using the other member selection operator ., which works directly on the object:- obj.func(args)
See operator precedence

Other Uses for member selection: -> .

None, Although . is also used as a decimal point of course!

Usage Notes

An Alternative to ->

Writing:- *objptr.func(args) does not achieve the same result as the selection is of higher priority so actually means:-
  1. Treat objptr as an object and call its func.
  2. Take what results as a pointer and find the object it points to.
The correct syntax requires brackets to change the order:- (*objptr).func(args) which is why the more transparent:- objptr->func(args) was introduced.

Chaining ->

It is not uncommon for an object to have a member function that returns a pointer to another object. The returned object can then be sent a sent a message. The example, suppose:- then, because the -> operator associates left to right, the statement:- objptr_a -> GetB() -> Print(); gets B from A and sends it the print message.
Go Back to the The C++ Crib Top Page

If you have any comments about this page please send them to Nick West