The arrow operator -> in C++ is used to access the members of the class or structure.
In C++, you can use this arrow operator to access the members of the class, structure, and union with the help of pointers. It helps in memory management, linked-list data structures, and object-oriented programming.
In this article, we will discuss the definition, relationships, common use cases, and prevention of common errors while using the arrow operator in C++.
Table of Contents:
Arrow Operator in C++
The arrow operator (->) is a way or short path to access the members of a class, structure, or union using pointers. It is made up of a combination of two different operators, the minus operator (-) and the greater than operator (>). That’s why it combines two operations, dereferencing the pointer and accessing the member.
Syntax of the Arrow Operator
The syntax of the arrow operator is:
pointer_variable -> class_member_name;
Here,
- pointer_variable is a pointer pointing to the class or structure.
- class_member_name is the name of the member or function in the pointed structure or class.
Example:
#include <iostream>
struct Point {
int x, y;
};
int main() {
Point p1 = {10, 20}; // Normal structure variable
Point* ptr = &p1; // Pointer to structure
// Accessing members using the arrow operator
std::cout << "X: " << ptr->x << ", Y: " << ptr->y << std::endl;
return 0;
}
Output:
In this code, X and Y are the two integer members of the structure named as the point, and the pointer point p1 is initialized with the values. The arrow operator is used with the initialized pointer ptr to access the members, with the output printing to the console.
Relationship between Pointers and Structures/Classes in C++
In C++, pointers provide an efficient way for memory management and allocation, and structures or classes have members or functions that are using the memory. So, since pointers store the memory addresses or locations, the arrow operator helps to access the members from the structure or class using pointers.
Example:
#include <iostream>
struct Person {
std::string name;
int age;
};
int main() {
// Dynamic memory allocation
Person* p = new Person{"Alice", 25};
std::cout << "Name: " << p->name << ", Age: " << p->age << std::endl;
// Free allocated memory
delete p;
return 0;
}
Output:
In this code, person is the structure with the two members’ name and age. The arrow operator is used to access the members with the initialized pointer p, and then the output is printed to the console.
Common Use Cases of the Arrow Operator in C++
Below are a few common use cases of the arrow operator in C++:
1. Arrow Operators in Structures in C++
In C++, structures are used to group or combine the related data together. Using the arrow operators in structures helps to access the members of the structure through a pointer.
Example:
#include <iostream>
struct Student {
std::string name;
int rollNumber;
float marks;
};
int main() {
// Dynamically allocate memory for a Student structure
Student* stu = new Student{"Pooja Shree", 101, 89.5};
// Access members using the arrow operator
std::cout << "Student Name: " << stu->name << std::endl;
std::cout << "Roll Number: " << stu->rollNumber << std::endl;
std::cout << "Marks: " << stu->marks << std::endl;
// Free allocated memory
delete stu;
return 0;
}
Output:
In this code, student is the structure with the three members: student name, roll number, and marks. The arrow operator is used with the initialized pointer newSudent to access the data members, and then the output is printed on the console.
2. Arrow Operators in Unions in C++
The arrow operator can also be used with the unions. In C++, a union is a data structure where all members share the same memory location. So while dealing with unions, we can access their members using the arrow operator through the pointer.
Example:
#include <iostream>
union Data {
int intValue;
float floatValue;
char charValue;
};
int main() {
Data* ptr = new Data; // Dynamically allocate memory for the union
ptr->intValue = 42; // Assign an integer value
std::cout << "Integer Value: " << ptr->intValue << std::endl;
ptr->floatValue = 3.14f; // Now, assign a float value (overwrites int)
std::cout << "Float Value: " << ptr->floatValue << std::endl;
ptr->charValue = 'A'; // Now, assign a character (overwrites float)
std::cout << "Char Value: " << ptr->charValue << std::endl;
delete ptr; // Free allocated memory
return 0;
}
Output:
In this code, Data is a union with the three members: intValue, floatValue, and charValue. The arrow operator is used with the initialized pointer newData to access the data members and prints the output of int, char, and float one by one.
3. Arrow Operator in Classes in C++
In C++, the arrow operator is used to access the class members very efficiently, as a class is a user-defined data type that is used to create an object in object-oriented programming, and using the arrow operator makes it easier to work with the classes in C++.
Example:
#include <iostream>
class Company {
public:
void welcome() {
std::cout << "Welcome to Intellipaat!" << std::endl;
}
};
int main() {
Company* companyPtr = new Company(); // Dynamically allocate object
companyPtr->welcome(); // Call function using arrow operator
delete companyPtr; // Free memory
return 0;
}
Output:
In this code, Company is a class with a member function welcome(). The arrow operator is used to access the member function by using the initialized pointer new Company() and prints the output to the console.
4. Arrow Operator in Linked List in C++
In C++, a linked list is a data structure that is made up of sequential nodes, where each node contains a value and a pointer to the next node. The arrow operator is used in the linked list to access the data and pointers of the list using the other pointers, as these are the members of a linked list.
Example:
#include <iostream>
struct Node {
int data;
Node* next;
};
int main() {
// Creating nodes dynamically
Node* head = new Node{10, nullptr};
head->next = new Node{20, nullptr};
head->next->next = new Node{30, nullptr};
// Traversing the linked list
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " -> ";
temp = temp->next;
}
std::cout << "NULL" << std::endl;
// Free allocated memory
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
return 0;
}
Output:
In this code, the arrow operator is used to access the members of a linked list, data, and next by using the initialized pointer new Node, and the output is printed to the console after reaching the end of the list.
Preventions to Avoid Common Errors for Arrow Operators
- Always initialize the pointers and check for the null pointers, so then they cannot access the invalid members of the class or structure.
- Use smart pointers to manage memory corruption and access the data members efficiently.
- Always check for the end of the list in a linked list before accessing it.
- Always access only the member that is written last in unions, otherwise, it will show an error while accessing the data members.
Comparison of the (->) Arrow Operator with the (.) Dot Operator in C++
In C++, both the arrow operator (->) and the dot operator (.) are used to access the data members of the structure or class. The only difference between both operators is that the dot operator (.) accesses the members directly without using the pointers, and the arrow operator (->) accesses the members using the pointers.
Features | Arrow operator (->) | Dot operator (.) |
Used to access data members | Indirectly, using pointers | Directly, using pointers |
Used with | Normal objects | Pointer objects |
Dereferencing required | No | Yes |
Notation | (*ptr).member | (ptr)->member |
Example: Using both the dot operator (.) and the arrow operator (->)
#include <iostream>
struct Car {
std::string brand;
int year;
};
int main() {
Car car1 = {"Toyota", 2022}; // Normal object
Car* carPtr = &car1; // Pointer to the object
// Using dot operator
std::cout << "Brand: " << car1.brand << ", Year: " << car1.year << std::endl;
// Using arrow operator
std::cout << "Brand: " << carPtr->brand << ", Year: " << carPtr->year << std::endl;
return 0;
}
Output:
In this code, both the dot operator (.) and the arrow operator (->) are used to access the data members of the class Car. The arrow operator accesses the member’s brand and year using the initialized pointers, and the dot operator (.) accesses the members directly. Then, the output is printed twice to show the use of both operators.
Operator Overloading for Arrow Operator in C++
In C++, the arrow operator is overloaded to manage the custom behavior while accessing the data members of a class or structure using the pointer. The overloaded arrow operator is used with smart pointers and iterators. It is an efficient manner to deal with the customized requirements of the class while accessing the members.
Example:
#include <iostream>
class Data {
public:
void show() {
std::cout << "Inside Data class" << std::endl;
}
};
class Wrapper {
private:
Data* ptr; // Pointer to Data class
public:
Wrapper(Data* p) : ptr(p) {}
// Overloading the arrow operator
Data* operator->() {
return ptr;
}
};
int main() {
Data obj;
Wrapper wrap(&obj);
wrap->show(); // Equivalent to obj.show()
return 0;
}
Output:
In this code, the arrow operator is overloaded to define or manage the custom behavior of the class Data using the initialized pointer, which is managed by the Wrapper class to show the accessed members.
- Use the arrow operator with raw pointers to directly access the members.
- Using the arrow operator excessively can lead to poor CPU cache and high memory usage.
- Excessive use of the overloaded arrow operator also leads to low performance and slow execution of the codes.
- Debugging the overloaded arrow operator is a complex task due to the multiple warnings and errors.
- The code should be benchmarked properly while using the arrow operators to manage the efficiency.
Conclusion
In C++, the arrow operator plays an important role in accessing the members of the class or structures efficiently by using the pointers. The use of the arrow operator makes code more efficient and readable, as it combines the function of the (-) operator and the (>) operator. So, by understanding the use cases, relationships, and preventions of the arrow operator, we can enhance our C++ programming skills.