This article aims to discuss arrow operator in C++.
What is Arrow Operator in C++?
The arrow operator, denoted by “->”, is a binary operator in C++ that allows for the accessing of a member of a structure, union, or class through a pointer. It is used to access class members using a pointer variable. It’s also called a “Class Member Access Operator” in the C++ programming language.
The main advantage of using arrow operator in C++ is that it simplifies the code by allowing direct access to members of a class without the need for explicit dereferencing of the pointer.
Syntax
The syntax for the arrow operator is:
Here, the object_pointer_name is the name of the pointer to the object, and the member_name is the name of the member variable or member function of the class.
Use an Arrow Operator in C++
Let’s consider an example of how the arrow operator works in C++. In the following program, we define a class “student” with two member variables: cgpa and sem.
using namespace std;
class student
{
private:
float cgpa;
public:
int sem;
void init(float cgpa)
{
this->cgpa = cgpa;
}
void display()
{
cout << "cgpa = " << cgpa << endl;
}
};
int main()
{
student *st = new student();
cout << "Using * and . Operators\n";
(*st).init(3.97);
(*st).sem = 5;
(*st).display();
cout << "sem = " << (*st).sem << endl;
cout << "Using Arrow Operator (->)\n";
st->init(3.97);
st->sem = 5;
st->display();
cout << "sem: " << st->sem << endl;
return 0;
}
After making classes and objects, we called the main() function. We created an object in the main function “st” of the student class using a pointer. The arrow operator (->) was then used to give the value “3.97” and ”5” to be stored in the member variables cgpa and sem respectively. After the assignment of the values to the members, we applied the arrow operator (->) to reach the members and print its value, as shown in the output.
Output
Conclusion
The arrow operator (->) is an essential operator in C++ programming that allows access to class members using a pointer variable. It is easy to use and saves time compared to using the combination of the asterisk (*) and dot (.) operators. By understanding how to use the arrow operator in C++, programmers can easily manipulate object-oriented programming concepts, especially when dealing with pointers.