39

is there, and if, what it does?

.*
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
hash
  • 1,141
  • 1
  • 12
  • 20

2 Answers2

42

Yes, there is. It's the pointer-to-member operator for use with pointer-to-member types.

E.g.

struct A
{
    int a;
    int b;
};

int main()
{
    A obj;
    int A::* ptr_to_memb = &A::b;

    obj.*ptr_to_memb = 5;

    ptr_to_memb = &A::a;

    obj.*ptr_to_memb = 7;

    // Both members of obj are now assigned
}

Here, A is a struct and ptr_to_memb is a pointer to int member of A. The .* combines an A instance with a pointer to member to form an lvalue expression referring to the appropriate member of the given A instance obj.

Pointer to members can be pointers to data members or to function members and will even 'do the right thing' for virtual function members.

E.g. this program output f(d) = 1

struct Base
{
    virtual int DoSomething()
    {
        return 0;
    }
};

int f(Base& b)
{
    int (Base::*f)() = &Base::DoSomething;
    return (b.*f)();
}

struct Derived : Base
{
    virtual int DoSomething()
    {
        return 1;
    }
};

#include <iostream>
#include <ostream>

int main()
{
    Derived d;
    std::cout << "f(d) = " << f(d) << '\n';
    return 0;
}
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
15

You may come across that operator when using member pointers:

struct foo
{
    void bar(void);
};

typedef void (foo::*func_ptr)(void);

func_ptr fptr = &foo::bar;
foo f;

(f.*fptr)(); // call

Also related is the ->* operator:

func_ptr fptr = &foo::bar;
foo f;
foo* fp = &f;

(fp->*fptr)(); // call
GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • 1
    It's not a combination -- it really is a single operator (per §§ 2.12, 5.5 of the standard). FWIW, `->*` is also a single operator (same references). – Jerry Coffin Mar 30 '10 at 20:50
  • @sbi: What are you talking about...? :) @Jerry: I meant combination of actual symbols, not combination of operators. I suppose it is confusing. – GManNickG Mar 30 '10 at 20:51
  • 1
    @GMan -- yup. I have to admit I was a bit surprised at the idea you wouldn't have known it was a single operator... – Jerry Coffin Mar 30 '10 at 20:52
  • @GMan: Um, I thought, for moment, you had written "member _function_ pointer" there. Sorry. `` – sbi Mar 31 '10 at 07:22
  • @sbi: I actually had, I edited it out shortly after posting. :) You caught me. – GManNickG Mar 31 '10 at 08:17