What is the '-->' operator in C/C++?
What is the -->
Operator in C/C++?
In C and C++, the ->
operator is used for accessing members of a structure or class through a pointer. It is not the same as the .
operator, which is used to access members directly from an object. The ->
operator combines dereferencing a pointer and accessing a member in one step.
Syntax and Usage
Syntax:
pointer->member
Usage:
pointer
is a pointer to a structure or class.member
is a member of the structure or class.
When you have a pointer to a structure or a class, you use the ->
operator to access its members instead of using the dereference operator *
followed by the dot operator .
.
Example with Structures
Consider the following structure in C:
#include <stdio.h> struct Person { char name[50]; int age; }; int main() { struct Person person = {"John Doe", 30}; struct Person *ptr = &person; // Accessing members using the pointer and the -> operator printf("Name: %s\n", ptr->name); printf("Age: %d\n", ptr->age); return 0; }
In this example:
ptr
is a pointer to aPerson
structure.ptr->name
accesses thename
member of the structure pointed to byptr
.ptr->age
accesses theage
member of the structure pointed to byptr
.
Example with Classes
In C++, the ->
operator is used similarly with classes:
#include <iostream> #include <string> class Person { public: std::string name; int age; Person(std::string n, int a) : name(n), age(a) {} }; int main() { Person person("John Doe", 30); Person *ptr = &person; // Accessing members using the pointer and the -> operator std::cout << "Name: " << ptr->name << std::endl; std::cout << "Age: " << ptr->age << std::endl; return 0; }
In this example:
ptr
is a pointer to aPerson
object.ptr->name
accesses thename
member of the object pointed to byptr
.ptr->age
accesses theage
member of the object pointed to byptr
.
Summary
The ->
operator in C and C++ is used to access members of a structure or class through a pointer. It combines the dereferencing of the pointer and accessing the member into one operation. This operator is essential when working with pointers to structures or classes, allowing for more concise and readable code.
For a deeper understanding of C++ pointers and more advanced topics, consider exploring courses like Grokking the Coding Interview on DesignGurus.io. This course covers essential coding and algorithm techniques that can help you master programming concepts and succeed in technical interviews.
GET YOUR FREE
Coding Questions Catalog