• Home
  • 3.24 Pointer Member Operator (->)

3.24 Pointer Member Operator (->)

View Categories

3.24 Pointer Member Operator (->)

1 min read

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 the student object.
  • ptr->name accesses the name member of the object pointed to by ptr.
  • ptr->age accesses the age member of the object pointed to by ptr.
  • The expression ptr->member is 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.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *