Home >Backend Development >C++ >How Do C \'s `->*` and `.*` Pointer-to-Member Operators Work?

How Do C \'s `->*` and `.*` Pointer-to-Member Operators Work?

Susan Sarandon
Susan SarandonOriginal
2024-11-26 16:35:14838browse

How Do C  's `->*` and `.*` Pointer-to-Member Operators Work?
*` and `.*` Pointer-to-Member Operators Work? " />

Understanding Pointer-to-Member Operators -> and . in C

Despite existing documentation, grasping the meaning of pointer-to-member operators -> and . in C can be elusive. This article aims to clarify their functionality and their application in various scenarios.

What are -> and .?

Pointer-to-member operators are used to access member functions indirectly through pointers or references to objects. -> dereferences a member function pointer to call a member function of the referenced object. . dereferences a member pointer to call a member function of the pointed object.

When to Use -> and .?

  • Use ->* when you have a pointer to an object:
X* px = new X;
pointer somePointer = &X::f;
(px->*somePointer)(); // Calls px->f()
  • Use .* when you have a reference to an object:
X& rx = x;
pointer somePointer = &X::f;
(rx.*somePointer)(); // Calls rx.f()
  • Don't use x.somePointer() or px->somePointer(): These syntaxes are invalid because they attempt to call non-existent member functions.

Example

Consider the following code:

struct X
{
   void f() {}
   void g() {}
};

int main()
{
   X x;
   void (X::*pointer)() = &X::f;

   // Call x.f() using .*
   (x.*pointer)();

   X* px = new X;

   // Call px->f() using ->*
   (px->*pointer)();

   return 0;
}

In this example, pointer dereferences the member function pointer &X::f and assigns it to pointer. Then, . is used on x to call x.f(), and -> is used on px to call px->f().

By understanding the difference between -> and . and when each one is appropriate, developers can effectively handle member function pointers and indirect function calls in C .

The above is the detailed content of How Do C \'s `->*` and `.*` Pointer-to-Member Operators Work?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn