. and -> Member Access Operators

Access to members of Structures (and members of other object data types) is carried out using . dot notation, or by the shorthand little arrow -> member pointer dereferencing operator (aka member selection operator).

 

Given a structure:

 

struct rider {

char *team ;

int pos ;

} smith, marquez = { "Honda", 1 } ;

 

We can access the members using the . dot operator like so:

 

smith.team = "Monster Yamaha Tech 3" ; //set the team of the rider struct called smith

 

cout << marquez.team ;  //get the team of the rider struct called marquez

 

 

Alternatively, members of a struct can be accessed by member pointer dereferencing, carried out using the little arrow -> like so:

 

rider *ptr = &marquez ;  //first we define a pointer to the object

 

cout << ptr->team ;  //we can now use the -> to select the member

 

The -> dereferences the pointer and accesses the specified member.

 

*Note:  (*ptr).member is entirely equivalent to ptr->member, but is much easier to write.

 

#include <iostream>
using namespace std;

//declare a structure (user defined data type) called rider, with 2 objects called: smith, marquez
struct rider {
	string team;
	int pos;
} smith, marquez={"Honda", 1};

//function prototype called details, accepting rider (data type) pointer called *someLabel
void details (rider *someLabel);

int main () {

	smith.team = "Monster Yamaha Tech 3" ;	//set team member for smith object

	cout << smith.team << endl ;	//get team member for smith object

	rider *ptr = &marquez ; //initialise a struct rider pointer to marquez

	cout << ptr->team << endl ; //display team using member pointer dereferencing; ptr->

	details(ptr) ;	//call function, sending pointer to marquez as parameter

	ptr=&smith ;	//re-define struct rider pointer to address of smith

	ptr->pos = 9 ;	//set pos member for smith object

	details(ptr) ;	//call function, sending pointer to smith as parameter

	return 0;
}

void details (rider *ptr) {
	cout << ptr->team;
	cout << " is in position " << ptr->pos << endl ;
}

Compile & Run:

Monster Yamaha Tech 3
Honda
Honda is in position 1
Monster Yamaha Tech 3 is in position 9

Leave a Reply