Thursday, May 6, 2010

Pointer-to-Member Operators: .* and ->*


expression .* expression
expression –>* expression
The pointer-to-member operators, .* and –>*, return the value of a specific class member for the object specified on the left side of the expression. The right side must specify a member of the class. The following example shows how to use these operators:

// expre_Expressions_with_Pointer_Member_Operators.cpp
// compile with: /EHsc
#include 

using namespace std;

class Testpm {
public:
   void m_func1() { cout << "m_func1\n"; }
   int m_num;
};

// Define derived types pmfn and pmd.
// These types are pointers to members m_func1() and
// m_num, respectively.
void (Testpm::*pmfn)() = &Testpm::m_func1;
int Testpm::*pmd = &Testpm::m_num;

int main() {
   Testpm ATestpm;
   Testpm *pTestpm = new Testpm;

// Access the member function
   (ATestpm.*pmfn)();
   (pTestpm->*pmfn)();   // Parentheses required since * binds
                        // less tightly than the function call.

// Access the member data
   ATestpm.*pmd = 1;
   pTestpm->*pmd = 2;

   cout  << ATestpm.*pmd << endl
         << pTestpm->*pmd << endl;
   delete pTestpm;
}

Output

m_func1
m_func1
1
2
In the preceding example, a pointer to a member, pmfn, is used to invoke the member function m_func1. Another pointer to a member, pmd, is used to access them_num member.
The binary operator .* combines its first operand, which must be an object of class type, with its second operand, which must be a pointer-to-member type.
The binary operator –>* combines its first operand, which must be a pointer to an object of class type, with its second operand, which must be a pointer-to-member type.
In an expression containing the .* operator, the first operand must be of the class type of, and be accessible to, the pointer to member specified in the second operand or of an accessible type unambiguously derived from and accessible to that class.
In an expression containing the –>* operator, the first operand must be of the type "pointer to the class type" of the type specified in the second operand, or it must be of a type unambiguously derived from that class.

For more on Func-pointer
http://www.newty.de/fpt/fpt.html

No comments:

Post a Comment