Core C++

Lesson 41 : Member Function Pointers

This C++ video tutorial explains C++ member function pointers. Member function pointers are like the function pointer from the previous lesson, except that they point to member functions instead of functions. Furthermore, they are scoped by class so that a member function pointer from one class cannot point to a member function of a another class.

The code sample below contains a loan class, which we can use to calculate the loan amount for a loan that has interest calculated annually or quarterly. The constructor takes the principal amount and the interest rate as parameters. Internally, we store the principal and interest rate as data members of the class.

#include <iostream> #include <cmath> class CLoan { public: CLoan(double dPrincipal, double dRate) : mdPrincipal(dPrincipal), mdRate(dRate) {} // A = P*(1.0 + r)^t double AmountAnnually(double dTimeInYears) { return mdPrincipal*pow((1.0 + mdRate), dTimeInYears); } // A = P*(1.0 + r/4)^4t double AmountQuarterly(double dTimeInYears) { return mdPrincipal*pow((1.0 + mdRate/4.0), 4.0*dTimeInYears); } private: double mdPrincipal; double mdRate; }; int main() { using namespace std; CLoan qLoan(1000.0, 0.043); double (CLoan::*pfnAmount)(double); pfnAmount = &CLoan::AmountAnnually; cout << "Amount Annually = " << (qLoan.*pfnAmount)(10.0) << endl; pfnAmount = &CLoan::AmountQuarterly; cout << "Amount Quarterly = " << (qLoan.*pfnAmount)(10.0) << endl; return 0; }

Our class contains member functions for calculating the amount for interest that is calculated annually or quarterly. In our main function, we declare a loan object and the member function pointer, pfnAmount. Then we set the pointer to point to the calculation function for quarterly or annually compounded interest and out put the amount owed after 10 years with the compounded interest.

To call the interest functions with the member function pointer, we use the dot-dereference operator (.*). If the we wanted to call the function that the member function pointer points to with a pointer to an object, instead of the object, then we would use the arrow-dereference operator (->*).

This simple financial class is used here to give an easy demonstration of the use of member function pointers. By changing the pointer, we can vary which function is called and how we calculate interest on a loan.

 

© 2007–2024 XoaX.net LLC. All rights reserved.