(This question has been asked in GU Uni Dec 2018 for 7 Mark)

The -> (arrow) operator is used to access structure or C++ class members using a pointer. 

The dot and arrow operator are both used in C++ to access the members of a class. They are just used in different scenarios. In C++, types declared as a class, struct, or union are considered “of class type”. So the following refers to both of them.

  • a.b is only used if b is a member of the object (or reference[1] to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class.
  • a →b is essentially a shorthand notation for (*a).b, ie, if a is a pointer to an object, then a→b is accessing the property b of the object that points to.

Note that dot (.) operator is not overloadable and arrow (→) is an overloadable operator

For Example

#include <iostream>
using namespace std; 
class Student
{
    int rollno; 
    int marks; 
    public:
    void setData(int r, int m)
    {
        rollno=r; 
        marks=m; 
    }
    void getData()
    {
        cout<<"Roll No: "<<rollno<<endl; 
        cout<<"Marks: "<<marks<<endl;
    }
};

int main()
{
    Student obj1;  
    obj1.setData(54,33); 
    obj1.getData(); 
    Student *p=&obj1; 
    p->getData(); 
    (*p).getData(); 
    return 0; 

}

Output

Roll No: 54
Marks: 33
Roll No: 54
Marks: 33
Roll No: 54
Marks: 33

https://github.com/amitntrivedi/ObjectOrientedConceptsandProgramming/blob/master/Classes%20And%20Objects/ArrowOperator.cpp

What is an Arrow Operator? Explain with an example.

Leave a Reply

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