0

Good day,

I've come across this question, but I'm specifically interested in the "object pointed to by member ..." type operators as listed here on Wikipedia.

I have never seen this in the context of actual code, so the concept appears somewhat esoteric to me.

My intuition says they should be used as follows:

struct A
{
    int *p;
};

int main()
{
    {
        A *a = new A();
        a->p = new int(0);
        // if this did compile, how would it be different from *a->p=5; ??
        a->*p = 5;
    }

    {
        A a;
        a.p = new int(0);
        // if this did compile, how would it be different from *a.p=5; ??
        a.*p = 5;
    }

    return 0;
}

But this doesn't compile because p is undeclared. (See example)

Could anyone please provide a real-world example of the use of operator->* and/or .* in C++?

Community
  • 1
  • 1
namezero
  • 2,203
  • 3
  • 24
  • 37

2 Answers2

6

Those operators are used for pointer-to-member objects. You won't come across them very often. They can be used to specify what function or member data to use for a given algorithm operating on A objects, for instance.

Basic syntax:

#include <iostream>

struct A
{
    int i;
    int geti() {return i;}
    A():i{3}{}
};

int main()
{
    {
        A a;
        int A::*ai_ptr = &A::i; //pointer to member data
        std::cout << a.*ai_ptr; //access through p-t-m
    }

    {
        A* a = new A{};
        int (A::*ai_func)() = &A::geti; //pointer to member function
        std::cout << (a->*ai_func)(); //access through p-t-m-f
    }

    return 0;
}
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • Ok, so they're only used in the context of pointer to members. I had the entire concept wrong. Not part of the original question, but why would one want to overload that operator though? The linked question's answer misses that part. – namezero Jul 01 '15 at 11:00
0

The ->* and .* syntax is the "pointer-to-member" operator that can be used to store pointers to members of a very specific object.

Usage example:

class A {
    public: int x;
};

int main() {
    A obj;
    int A::* memberPointer = &A::b;  //Pointer to b, which is int, which is member of A
    obj.*memberPointer = 42; //Set the value via an object

    A *objPtr = &obj;
    objPtr->*memberPointer = 21;  //Set the value via an object pointer
}
maja
  • 17,250
  • 17
  • 82
  • 125