Table of Contents
The pointer member operator (->) is used to access the members of an object through a pointer. It combines pointer dereferencing and member access into a single operator, making the syntax simpler and more readable.
The expression pointer->member is equivalent to (*pointer).member. The pointer member operator is commonly used when working with dynamically allocated objects and object pointers.
Source Code #
#include <iostream>
struct Student
{
std::string name;
int age;
};
int main()
{
Student student = {"Alice", 20};
Student* ptr = &student;
std::cout << "Name: " << ptr->name << '\n';
std::cout << "Age : " << ptr->age << '\n';
return 0;
}
Output #
Name: Alice
Age : 20
Explanation #
- The pointer member operator (
->) accesses the members of an object through a pointer. Student* ptr = &student;declares a pointer that stores the address of thestudentobject.ptr->nameaccesses thenamemember of the object pointed to byptr.ptr->ageaccesses theagemember of the object pointed to byptr.- The expression
ptr->memberis equivalent to(*ptr).member. - The pointer member operator is used only with pointers to objects.
- It simplifies member access by combining dereferencing and the dot operator into a single operation.
return 0;terminates the program successfully.