1. Computing

C++ Tutorial - Advanced Pointers

By

7 of 8

About Class Function Methods
The address of a function is obtained by assigning the function name without brackets. If the function is getValue(), then getValue is the address and this is what you assign. So far though we've only used non class functions. What if we want to call a member of a class through a function pointer? The example below does this.

Download example 3 ex3.cpp - Using Class Member functions via pointers.

Using Class Member Function Pointers

Lets pretend that static class functions don't exist for now as those haven't been covered in a tutorial yet. That leaves class member functions. In example two, the function MyFunc() was not part of a class. It existed in isolation. But realistically we may well want to call class member functions through a pointer.

Here is the problem. It doesn't make sense to just take the address of a class member function (which is what we did with MyFunc) because we don't know which instance of the class we mean. What if we had an array of ten objects. Which one would it use? It needs the object as well as the function.

Defining the variable to hold the function is more or less the same as before. The syntax though is a bit uglier because the class is used. First the variable is declared to hold the class function pointer.

   int (CList::*m_pointerToMember)(pElement) ;
 
This has to have the class prefix CList:: or else the compiler will treat it as a non class function pointer. Likewise, anywhere it is assigned- in this function
  void SetCallback( int (CList::*newpointerToMember)(pElement)) ;
 
also requires the same treatment and the function assigned in List.SetCallback must be specified though you have the choice of either
 CList::MyFuncB
 
or
 List.MyFuncB
 
Either will do though my preference is the latter.

On the next page : A recap on the syntax of Function Pointers

Related Video
Excel Autosum Function
Live Trace in Illustrator
  1. About.com
  2. Computing
  3. C / C++ / C#
  4. C++ Programming
  5. Learn C++ Programming
  6. About Class Function Methods

©2014 About.com. All rights reserved.