C++ Member (dot & arrow) Operators

The . (dot) operator and the -> (arrow) operator are used to reference individual members of classes, structures, and unions.

The dot operator is applied to the actual object. The arrow operator is used with a pointer to an object. For example, consider the following structure −

structEmployee{char first_name[16];int  age;}  emp;

The (.) dot operator

To assign the value “zara” to the first_name member of object emp, you would write something as follows −

strcpy(emp.first_name,"zara");

Example

#include <iostream>#include <cstring>usingnamespace std;structEmployee{char first_name[20];};intmain(){
    Employee emp;// Using dot operator to assign a valuestrcpy(emp.first_name,"zara");

    cout <<"First Name: "<< emp.first_name << endl;return0;}

When executed, this program outputs:

First Name: zara

The (->) arrow operator

If p_emp is a pointer to an object of type Employee, then to assign the value “zara” to the first_name member of object emp, you would write something as follows −

strcpy(p_emp->first_name,"zara");

The -> is called the arrow operator. It is formed by using the minus sign followed by a greater than sign.

Example

#include <iostream>#include <cstring>usingnamespace std;structEmployee{char first_name[20];};intmain(){
    Employee emp;
    Employee* p_emp =&emp;// Using arrow operator to assign a valuestrcpy(p_emp->first_name,"zara");

    cout <<"First Name: "<< p_emp->first_name << endl;return0;}

When executed, this program outputs:

First Name: zara

Simply saying: To access members of a structure, use the dot operator. To access members of a structure through a pointer, use the arrow operator.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *