Declarations of pointers to members are special cases of pointer declarations.
Syntax
decl-specifiers class-name :: * cv-qualifier-listopt dname ;
A pointer to a member of a class differs from a normal pointer because it has type information for the type of the member and for the class to which the member belongs. A normal pointer identifies (has the address of) only a single object in memory. A pointer to a member of a class identifies that member in any instance of the class. The following example declares a class, Window
, and some pointers to member data.
class Window
{
public:
Window(); // Default constructor.
Window( int x1, int y1, // Constructor specifying
int x2, int y2 ); // window size.
BOOL SetCaption( const char *szTitle ); // Set window caption.
const char *GetCaption(); // Get window caption.
char *szWinCaption; // Window caption.
};
// Declare a pointer to the data member szWinCaption.
char * Window::* pwCaption = &Window::szWinCaption;
In the preceding example, pwCaption
is a pointer to any member of class Window
that has type char*. The type of pwCaption
is char * Window::*
. The next code fragment declares pointers to the SetCaption
and GetCaption
member functions.
const char * (Window::*pfnwGC)() = &Window::GetCaption;
BOOL (Window::*pfnwSC)( const char * ) = &Window::SetCaption;
The pointers pfnwGC
and pfnwSC
point to GetCaption
and SetCaption
of the Window
class, respectively. The code copies information to the window caption directly using the pointer to member pwCaption
:
Window wMainWindow;
Window *pwChildWindow = new Window;
char *szUntitled = "Untitled - ";
int cUntitledLen = strlen( szUntitled );
strcpy( wMainWindow.*pwCaption, szUntitled );
(wMainWindow.*pwCaption)[cUntitledLen - 1] = '1'; //same as
//wMainWindow.SzWinCaption [ ] = '1';
strcpy( pwChildWindow->*pwCaption, szUntitled );
(pwChildWindow->*pwCaption)[szUntitledLen - 1] = '2'; //same as
//pwChildWindow->szWinCaption[ ] = '2';
The difference between the .* and –>* operators (the pointer-to-member operators) is that the .* operator selects members given an object or object reference, while the –>* operator selects members through a pointer. (For more about these operators, see Expressions with Pointer-to-Member Operators in Chapter 4.)
The result of the pointer-to-member operators is the type of the member — in this case, char *.
The following code fragment invokes the member functions GetCaption
and SetCaption
using pointers to members:
// Allocate a buffer.
char szCaptionBase[100];
// Copy the main window caption into the buffer
// and append " [View 1]".
strcpy( szCaptionBase, (wMainWindow.*pfnwGC)() );
strcat( szCaptionBase, " [View 1]" );
// Set the child window's caption.
(pwChildWindow->*pfnwSC)( szCaptionBase );