
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is Arrow Operator in C++
The array operator provides the direct access to array elements using their index.
What is Array Operator in C++?
The arrow operator in C++ is also known as the member access operator, which is used to access a member of a class, structure, or union with the help of a pointer to an object.
The arrow operator allows you to directly access the member, unlike the dot operator, which first dereferences the pointer and then uses the dot operator to access it. So instead of using (*pointer).member, you can directly use pointer->member.
Syntax
Here is the syntax to access array element using the arrow operator:
pointerName->memberName;
Where,
- pointerName is the name of a pointer that is pointing to an object.
- memberName is the name of a member, which you want to access from the object where the pointer points to.
Example of Arrow Operator
The following code is an example demonstrating the use of the arrow operator. Here, the arrow operator is used to access the object's members (name and age), and then the result is displayed. After using the object, the pointer is deleted to free the dynamically allocated memory that helps to prevent memory leaks.
In this, we didn't need to dereference the pointer to access the member, like in the dot operator.
#include <iostream> using namespace std; class Student { public: string name; int age; void display() { cout << "Name: " << name << ", Age: " << age << endl; } }; int main() { // creating a pointer to a Student object Student* ptr = new Student(); // accessing members using the arrow operator ptr->name = "Aman"; ptr->age = 21; // calling a member function using arrow function ptr->display(); // freeing the dynamically allocated memory delete ptr; return 0; }
Output
Name: Aman, Age: 21