Home > Backend Development > C++ > body text

What\'s the Difference Between C \'s `->*` and `.*` Pointer-to-Member Operators?

Linda Hamilton
Release: 2024-11-19 04:24:03
Original
590 people have browsed it

What's the Difference Between C  's `->*` and `.*` Pointer-to-Member Operators?
*` and `.*` Pointer-to-Member Operators? " />

Demystifying the Pointer-to-Member Operators -> and . in C

Despite having explored existing resources, you may still find yourself perplexed by the enigmatic -> and . operators in C . This article aims to shed light on their true nature and clarify when their use becomes necessary.

Understanding the Purpose of Pointer-to-Member Operators

Both -> and . are pointer-to-member operators that facilitate indirect access to member functions. This intricate terminology essentially means that they enable you to invoke a member function through a pointer rather than directly from an object.

Syntax and Usage

  • ->: This operator is used to dereference a pointer that points to a member function of an object. Its syntax is (ptr->member_func_ptr)().
  • .: Similar to ->, this operator also dereferences a pointer to a member function. However, it is used when the pointer is dereferenced through an object's pointer or class. Its syntax is (object_ptr.*member_func_ptr)().

When to Use -> vs. .

  • ->*: Use this operator when dereferencing a pointer to a member function through a pointer to an object.
  • .*: Use this operator when dereferencing a pointer to a member function through an object's pointer or class.

Example

Consider a class X with the following member functions: f() and g(). Suppose you have a pointer that points to the f() function:

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

typedef void (X::*pointer)();
pointer somePointer = &X::f;
Copy after login

To call somePointer using an object x, you would use:

X x;
(x.*somePointer)(); // Calls x.f()
Copy after login

If x is not an object but a pointer to an object, you can invoke the member function using ->* as follows:

X* px = new X;
(px->*somePointer)(); // Calls px->f()
Copy after login

This example illustrates that using ->> or . is crucial when accessing member functions indirectly through pointers, especially when dealing with pointed-to objects.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template