Ask the C++ Pro 10-Minute Solution

Pointing to Class Members

I've received a lot of questions lately such as this about pointers to class methods: "I work with Visual C++ 4.0. I cannot use the pointer of a class method. The compilation error message is:

Cannot convert parameter 2 from 'long (unsigned long)'
to
'long (__cdecl *)(unsigned long)'
What should I do?"

Here is the code for one way to solve this problem.



//in the header
class CKernel:
{
   long (*lpFunc)(DWORD);
   long OLESendTC( DWORD dwInfo );
}

//in the cpp File
BOOL CKernel::Init()
{
   lpFunc = OLESendTC;
   return TRUE;
}
Class methods all have one hidden argument, a pointer to the class object the method is called on. C++ uses this pointer to find the location of any class data that the method may reference. If you try and use a standard function pointer to call a class method, C++ has no way to pass this hidden argument and a conflict results.

To help deal with this and to improve type safety, C++ added three new operators, ::*, .*, and ->*, to allow for safe pointers to members. These pointers to members can point to either member functions or variables.



class CTest
{
public:
	BOOL Init();
	long OLESendTC(DWORD dwInfo);
};

long (CTest::*lpFunc)(DWORD dwInfo) = &CTest::OLESendTC;

int main()
{
	CTest test;
	(test.*lpFunc)(0);
	return 0;
}

long CTest::OLESendTC(DWORD dwInfo)
{
	cout << "IN OLESENDTC\n";
	return 0;
}
This example shows one use of pointers to members. The code uses the ::* operator to declare lpFunc as a pointer to a CTest member function. Note that, rather than assign a value to this pointer at run time, the pointer is simply initialized in the declaration.

In the main function, this example uses the .* operator to call the method pointed to by lpFunc. If test were a pointer here, you would use the ->* operator instead.

C++ has a lot of things going on under the hood such as hidden arguments to methods. Pointers to members allow you to safely declare a pointer to a class method and call methods through that pointer.

 
Other 10-Minute Solutions
 How to Change the Mouse Pointer without Flicker
 Setting Full Row Selection in ListView Control
 Automating Type Conversions with stringstream Objects
 Improving Memory Reallocation with Vectors
 How to Use <fstream> Classes for File I/O
 Casting About for Safe Typecasting
 Overloading Operator + the Right Way
 How to Create Persistent Objects
 Making Linked Lists More User-Friendly
 Preventing Glitches in Signal Processing
 Forcing Object Allocation on the Free-store
 Using String-Based Data Validation
 Implementing the 'Resource Acquisition Is Initialization' Idiom
 Simple Locks for Data Files
 Template Specializations
 Exception Handling
 Using Bit Fields in Data Optimization
 Using the Transform() Algorithm to Change a String's Case
 Use RTTI for Dynamic Type Identification
 Choosing the Right swap () Implementation
 Take Charge and Initialize Your Own Data
 Share Data Among Objects Using the Monostate Design Pattern
 String Manipulation Made Easy with std::string Algorithms
 Using typedef to Curb Miscreant Code
 Managing Objects' Construction Order
 Bitwise Operators: Combining Efficiency and Ease of Use
 Use Function Adapters to Extend Generic Algorithms' Usage
 Simplify Callback Dispatching with Enumerated Indexes
 Streamline Your Bulk I/O Operations with Stream Iterators
 Optimize Your Member Layout
 Preserve Code Safety with Conversion Operators
 Modify Your Base Class Interface in Derived Classes
 Tackle Common Programming Tasks Using the New <tuple> Library
 Use Local Classes for Proper Cleanup in Exception-enabled Apps
 Use multimap to Create Associative Containers with Duplicate Keys
 Enforcing Compile-time Constraints
 Facilitate Directory Operations with the <dirent.h> and <dir.h> Libraries
 Spruce Up Your Built-in Arrays
 Target 32- and 64-bit Platforms Together with a Few Simple Datatype Changes
 Restrict Object Allocation to Specific Memory Types
 Use the Pimpl Idiom to Reduce Compilation Time and Enhance Encapsulation
 Automate Resource Management with shared_ptr
 The Quick and Dirty Way to Add
 Pointing to Class Members
 Detecting Keystrokes While Your Application is Busy
 Linked Lists
 Programming the System Tray
 Create a "Universal" DLL
 Convert Path to Long Path Name
 Constructing an Object at a Pre-Determined Memory Position
 Declaring Classes and Member Functions in a Namespace
 Using the auto_ptr Class Template to Facilitate Dynamic Memory Management
 Using the random_shuffle() Algorithm to Randomize a Sequence of Elements
 Defining a Function Object
 Implementing the Singleton Design Pattern
 Declaring Function Pointers and Implementing Callbacks
 Overloading Operator << for a User-Defined Type
 Implementing a Stopwatch Class for Performance Measurements
 Creating and Accessing Environment Variables
 Executing an Object's Member Function in a Separate Thread
 Creating Heterogeneous Containers
 Overriding New and Delete
 Time and Date Manipulation
  Defining Functions with a Variable Argument List
 Optimize Abstract Operations with Function Templates




Sponsored Links


Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map
Jupiterweb networks

internet.comearthweb.comDevx.comClickZ

Search Jupiterweb:

Jupitermedia Corporation has four divisions:
JupiterWeb, JupiterResearch, JupiterEvents, and JupiterImages

Copyright 2004 Jupitermedia Corporation All Rights Reserved.
Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Jupitermedia Corporate Info | Newsletters | Tech Jobs | E-mail Offers