![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 an arrow operator, `->` in C++?
The dot and arrow operator are both used in C++ to access the members of a class or structure. They are just used in different scenarios. In C++, types declared as class, struct, or union are considered "of class type". So the following refers to all three of them.
a.b is only used if b is a member of the object (or reference 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, i.e., if a is a pointer to an object, then a->b is accessing the property b of the object that a points to.
Note that dot cannot be overloaded but -> can be overloaded, so we can define our own function(operator->()) that should be called when this operator is used. so if a is an object of a class that overloads operator-> (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented.
References are, semantically, aliases to objects, so I should have added "or reference to a pointer" to the as well. However, I thought this would be more confusing than helpful, since references to pointers (T*&) are rarely ever used.
Example Code
#include<iostream> class A { public: int b; A() { b = 5; } }; int main() { A a = A(); A* x = &a; std::cout << "a.b = " << a.b << "\n"; std::cout << "x->b = " << x->b << "\n"; return 0; }
Output
5 5