Pointers and Functions 

Pointers to Functions 
Introduction 
Imagine you are writing a program to process cylinderrelated calculations, that is, to get its diameter, its circumference, its areas, and volume. The formulas used are reviewed in our Geometric Formulas section. You could start your program as follows: 
#include <iostream> using namespace std; int main() { double Radius; Radius = 25.55; cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; return 0; } This would produce: Cylinder Summary Radius: 25.55 Press any key to continue... 
When we studied functions that return a value, we saw that the result of such a function can be assigned to a value locally declared in the calling function: #include <iostream> using namespace std; int main() { double Radius, Diameter; double CalculateDiameter(double R); Radius = 25.52; Diameter = CalculateDiameter(Radius); cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; cout << "\nDiameter: " << Diameter; return 0; } double CalculateDiameter(double Rad) { return Rad * 2; }
#include <iostream> using namespace std; int main() { double Radius, Circumference; double CalculateDiameter(double R); double CalculateCircumference(double D); Radius = 25.52; // Instead of calling the CalculateDiameter() function first and // assign it to another, locally declared variable, such as in // "double Diameter = CalculateDiameter(Radius)", we can call the // CalculateDiameter(Radius) directly when we are calling the // CalculateCircumference() function. // This is possible because the CalculateCircumference() function // takes an argument that is the result of calling the // CalculateDiameter() function. As long as we only need the // circumference and we don't need the diameter, we don't have // to explicitly call the CalculateDiameter() function. Circumference = CalculateCircumference(CalculateDiameter(Radius)); cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; cout << "\nCircumference: " << Circumference << endl; return 0; } double CalculateDiameter(double Rad) { return Rad * 2; } double CalculateCircumference(double Diam) { const double PI = 3.14159; return Diam * PI; }
DataType (*FunctionName)();
#include <iostream> using namespace std; int main() { void (*SomethingToDo)(void); return 0; } 
After declaring a pointer to a function, keep in mind that this declaration only creates a pointer, not an actual function. In order to use it, you must define the actual function that would carry the assignment the function is supposed to perform. That function must have the same return type and the same (number of) argument(s), if any. For example, the above declared pointer to function is of type void and it does not take any argument. you can define a function as follows: 
void MovieQuote() { cout << "We went through a lot of trouble because of you\n"; cout << "You owe us\n"; cout << "\tFrom \"Disorganized Crime\"\n"; }
With such an associated function defined, you can assign it to the name of the pointer to function as follows SomethingTodo = MovieQuote; This assignment gives life to the function declared as pointer. The function can then be called as if it had actually been defined. Here is an example: 
#include <iostream> using namespace std; void MovieQuote() { cout << "We went through a lot of trouble because of you\n"; cout << "You owe us\n"; cout << " From \"Disorganized Crime\"\n"; } int main() { void (*SomethingToDo)(); // Assign the MovieQuote() function to the pointer to function SomethingToDo = MovieQuote; // Call the pointer to function as if it had been defined already SomethingToDo(); return 0; }
This would produce:
We went through a lot of trouble because of you You owe us From "Disorganized Crime"
You can also type the keyword between the return type and the opening parenthesis. You can also declare a pointer to function for a function that returns a value. Remember that both functions must return the same type of value (they must have the same signature). Here is an example: 
#include <iostream> using namespace std; int Addition() { int a = 16, b = 442; return a + b; } int main() { int (*SomeNumber)(); // Assign the MovieQuote() function to the pointer to function SomeNumber = Addition; // Call the pointer to function as if it had been defined already cout << "The number is " << SomeNumber(); return 0; }
If you want to use a function that takes arguments, when declaring the pointer to function, provide the return type and an optional name for each argument. Here is an example: int (*SomeNumber)(int x, int y); When defining the associated function, besides returning the same type of value, make sure that the function takes the same number and type(s) of arguments. Here is an example: 
#include <iostream> using namespace std; int Addition(int a, int b) { return a + b; } int main() { int (*SomeNumber)(int x, int y); int x = 128, y = 5055; // Assign the MovieQuote() function to the pointer to function SomeNumber = Addition; // Call the pointer to function as if it had been defined already cout << x << " + " << y << " = " << SomeNumber(x, y); return 0; }
You can also create a programmerdefined type as a pointer to function. Here is the syntax to use: typedef (*TypeName)(Arguments); The typedef keyword must be used. The TypeName and its asterisk must be enclosed in parentheses. The name must follow the rules applied to objects so far. The TypeName must be followed by parentheses. If the pointer to function will take arguments, provide its type or their types between parentheses. Otherwise, you can leave the parentheses empty (but you must provide the parentheses). After creating such a custom type, the name of the type would be used as an alias to a pointer to function. Consequently, it can be used to declare a pointer to function. Here is an example: 
#include <iostream> using namespace std; int Addition(int a, int b) { return a + b; } int main() { // Creating a programmerdefined type typedef int (*AddTwoIntegers)(int x, int y); // Now, the AddsTwoIntegers name is a pointer to function // that can take two integers. It can be used for a declaration AddTwoIntegers TwoNumbers; int x = 128, y = 5055; TwoNumbers = Addition; // Call the pointer to function as if it had been defined already cout << x << " + " << y << " = " << TwoNumbers(x, y); return 0; }
This would produce:
128 + 5055 = 5183 Press any key to continue...
Practical Learning: Using a Pointer to Function 
#include <iostream> using namespace std; #include "Loan.h" double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods); double Addition(double Value1, double Value2) { return Value1 + Value2; } int main() { double (*AddValues)(double R, double T); double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod; double Periods; string PeriodName; cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal = GetPrincipal(); IntRate = GetInterestRate(); Period = GetPeriod(TypeOfPeriod, Periods); AddValues = Addition; InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); double Amount = AddValues(Principal, InterestAmount); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return 0; } if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: " << IntRate << "%"; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\nTotal Amount Paid: $" << Amount; cout << "\n==================================\n"; return 0; } . . . No Change 
This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $1500 Enter the Interest Rate (%): 12.55 How do you want to enter the length of time? 1  In Days 2  In Months 3  In Years Your Choice: 3 Enter the number of years: 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ================================== Estimate on loan  Principal: $1500 Interest: 12.55% Period: 2 Years  Interest paid on Loan: $376.5 Total Amount Paid: $1876.5 ================================== Press any key to continue... 
#ifndef LoanH #define LoanH namespace Finance { typedef double (*Add)(double R, double T); double InterestAmount(double P, double r, double t); } #endif 
#include <iostream> using namespace std; #include "Loan.h" double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods); double Addition(double Value1, double Value2) { return Value1 + Value2; } int main() { Finance::Add Plus; double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod; double Periods; string PeriodName; cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal = GetPrincipal(); IntRate = GetInterestRate(); Period = GetPeriod(TypeOfPeriod, Periods); Plus = TotalAmount; InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); double Amount = Plus(Principal, InterestAmount); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return 0; } . . . No Change return 0; } . . . 
#ifndef LoanH #define LoanH namespace Finance { typedef double (*Add)(double R, double T); typedef double (*Subtract)(double First, double Second); typedef double (*Multiply)(double First, double Second); typedef double (*Divide)(double First, double Second); double InterestAmount(double P, double r, double t); } #endif 
#if !defined MainH #define MainH #include <iostream> using namespace std; namespace Accessories { // Accessory Functions // This function adds two values double Addition(double Value1, double Value2) { return Value1 + Value2; } // This function takes two arguments. // It subtracts the second from the first double Subtraction(double Value1, double Value2) { return Value1  Value2; } // This function multiplies two numbers double Multiplication(double Value1, double Value2) { return Value1 * Value2; } // This function takes two arguments // If the second argument is 0, the function returns 0 // Otherwise, the first argument is divided by the second double Division(double Numerator, double Denominator) { if( Denominator == 0 ) return 0; // else is implied return Numerator / Denominator; } } // namespace Accessories namespace LoanProcessing { double GetPrincipal() { double P; cout << "Enter the Principal: $"; cin >> P; return P; } double GetInterestRate() { double r; cout << "Enter the Interest Rate (%): "; cin >> r; return r; } double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1  In Days"; cout << "\n2  In Months"; cout << "\n3  In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod; if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return static_cast<double>(Periods / 360); } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return static_cast<double>(Periods / 12); } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return static_cast<double>(Periods); } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; return 0.00; } } } #endif // MainH 
#include <iostream> using namespace std; #include "Main.h" #include "Loan.h" int main() { // Declare a variable of type Add, defined in the Finance namespace Finance::Add Plus; double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod; double Periods; string PeriodName; cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal = LoanProcessing::GetPrincipal(); IntRate = LoanProcessing::GetInterestRate(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); Plus = Accessories::Addition; InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); double Amount = Plus(Principal, InterestAmount); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return 0; } if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: " << IntRate << "%"; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\nTotal Amount Paid: $" << Amount; cout << "\n==================================\n"; return 0; } 
A Pointer to a Function as Argument 
your programming environmentUsing pointer to functions, a function can be passed as argument to another function. The function must be passed as a pointer. The argument is declared in a complete format as if you were declaring a function. Here is an example of a function that is passed a function as argument. double Circumference(double (*FDiam)(double R)) This Circumference() function takes one argument. The argument itself is a pointer to function. This argument itself takes a doubleprecision number as argument and it returns a doubleprecision value. The Circumference() function returns a doubleprecision number. It is important to know that the pointer to function that is passed as argument is declared completely, in this case as double (*FDiam)(double R) Although the FDiam declaration is accompanied by an argument, in this case R, this argument allows the compiler to know that FDiam takes an argument. This argument actually will not be processed by the Circumference() function when the Circumference() function is defined because the R argument does not belong to the Circumference() function. When calling the Circumference() function, you will use the FDiam argument as a variable in its own right, using its name, as in Circumference(Diameter) When defining the Circumference() function, you must process the pointer to function that it takes as argument. If this argument is an alias to a function that returns a value, you can call it and pass it the argument as we studied in the last section. If you want to involve the FDiam argument in any operation, you can declare a local variable to the Circumference() function. If the FDiam argument must be involved in an operation that involves a value external to the Circumference() function, you must pass that type of value as argument to the Circumference() function, unless you are using a global variable (we will study global variables when we review the issue of scopes). This means that, in most circumstances, the pointer to function passed as argument may be accompanied by at least one other argument. For example, if you want to use the FDiam as a diameter value to calculate the circumference (Circumference = Diameter * PI), you may have to declare it with an argument for the radius. It would be declared as follows: double Circumference(double (*FDiam)(double R), double Rad); The function can then be implemented as follows: 
double Circumference(double (*FDiam)(double R), double Rad) { double Circf; const double PI = 3.14159; Circf = (*FDiam)(Rad); return Circf * PI; }
Remember that, when declaring a function, the compiler does not care about the name(s) of the argument(s). If the function takes any, what the compiler cares about are the return type of the function, its name, and the type(s) of its argument(s), if any. Therefore, the above function could as well be declared as follows: double Circumference(double (*)(double R), double); This indicates that the Circumference() function takes two arguments whose names are not known. The first argument is a pointer to a function that takes one doubleprecision number as argument and returns a double. The second argument of the Circumference() function is also a doubleprecision number. The Circumference() function returns a doubleprecision number. This is what the program at this time would look like: 
#include <iostream> using namespace std; double Diameter(double); double Circumference(double (*D)(double R), double r); int main() { double Radius; Radius = 25.52; cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; cout << "\nCircumference = " << Circumference(Diameter, Radius) << endl; return 0; } double Diameter(double Rad) { return Rad * 2; } double Circumference(double (*FDiam)(double R), double Rad) { double Circf; const double PI = 3.14159; Circf = (*FDiam)(Rad); return Circf * PI; }
This would produce:
Cylinder Summary Radius: 25.52 Circumference = 160.347 Press any key to continue...
To simplify the declaration of a pointer to function, we saw that you can create a programmerdefined type using the typedef keyword. This can also help when passing a function as argument. Here is an example: typedef double (*FDiam)(double R); double Circumference(FDiam, double); When creating such a programmerdefined type, remember that you must give a name to the alias, in this case FDiam. After this creation, FDiam is an alias to a pointer to function of a doubleprecision type and which takes one doubleprecision number as argument. Remember, as we learned when studying functions that return a value, that the item on the right side of the return keyword can be a value or a complete expression. Therefore, you can simplify the implementation of the Circumference() function as follows: 
double Circumference(double (*FDiam)(double R), double Rad) { const double PI = 3.14159; return (*FDiam)(Rad) * PI; }
Practical Learning: Passing a Function as Argument 
#ifndef LoanH #define LoanH namespace Finance { typedef double (*Add)(double R, double T); typedef double (*Subtract)(double First, double Second); typedef double (*Multiply)(double First, double Second); typedef double (*Divide)(double First, double Second); double InterestAmount(double P, double r, double t); double Rate(double (*AP)(double A, double P), double a, double p, double t); } #endif 
#include "Loan.h" #pragma package(smart_init) namespace Finance { // Interest = Principal * rate * time in years double InterestAmount(double P, double r, double t) { return P * (r / 100) * t; } double Rate(double (*AP)(double A, double P), double a, double p, double t) { double AMinusP = (*AP)(a, p); double Pt = p * t; return (AMinusP / Pt) * 100; } } 
#if !defined MainH #define MainH . . . No Change namespace LoanProcessing { double GetAmount() { double A; cout << "Enter the future value: $"; cin >> A; return A; } . . . No Change #endif // MainH 
#include <iostream> #include "Main.h" #include "Loan.h" using namespace std; using namespace Accessories; int main() { double Principal, Amount, IntRate, Period, InterestAmount; int TypeOfPeriod; double Periods; string PeriodName; cout << "This program allows you to perform estimations on loans\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); Principal = LoanProcessing::GetPrincipal(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); IntRate = Finance::Rate(Subtraction, Amount, Principal, Period); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return 0; } if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n"; cout << "\nFuture Value: $" << Amount; cout << "\nPrincipal: $" << Principal; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n"; cout << "\nInterest on Loan: " << IntRate << "%"; cout << "\n==================================\n"; return 0; } 
This program allows you to perform estimations on loans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the future value: $4500 Enter the Principal: $3000 How do you want to enter the length of time? 1  In Days 2  In Months 3  In Years Your Choice: 3 Enter the number of years: 3 ================================== Estimate on loan  Future Value: $4500 Principal: $3000 Period: 3 Years  Interest on Loan: 16.6667% ================================== Press any key to continue... 
#if !defined MainH #define MainH #include <iostream> #include "Loan.h" using namespace std; namespace Accessories { // Accessory Functions // This function adds two values double Addition(double Value1, double Value2) { return Value1 + Value2; } // This function takes two arguments. // It subtracts the second from the first double Subtraction(double Value1, double Value2) { return Value1  Value2; } // This function multiplies two numbers double Multiplication(double Value1, double Value2) { return Value1 * Value2; } // This function takes two arguments // If the second argument is 0, the function returns 0 // Otherwise, the first argument is divided by the second double Division(double Numerator, double Denominator) { if( Denominator == 0 ) return 0; // else is implied return Numerator / Denominator; } } // namespace Accessories namespace LoanProcessing { double GetAmount() { double A; cout << "Enter the future value: $"; cin >> A; return A; } double GetPrincipal() { double P; cout << "Enter the Principal: $"; cin >> P; return P; } double GetInterestRate() { double r; cout << "Enter the Interest Rate (%): "; cin >> r; return r; } double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1  In Days"; cout << "\n2  In Months"; cout << "\n3  In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod; if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return static_cast<double>(Periods / 360); } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return static_cast<double>(Periods / 12); } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return static_cast<double>(Periods); } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; return 0.00; } } int SelectCalculationType() { int Answer; cout << "What kind of value do you want to estimate?"; cout << "\n1  Calculate (only) the interest paid on the loan"; cout << "\n2  Estimate the future value of the entire loan"; cout << "\nYour choice: "; cin >> Answer; return Answer; } void ProcessInterestAmount() { double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod; double Periods; string PeriodName; cout << "\nWe will calculate the interest amount payed on a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal = LoanProcessing::GetPrincipal(); IntRate = LoanProcessing::GetInterestRate(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return; } if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n"; cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: " << IntRate << "%"; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\n==================================\n"; } void ProcessRateOfInterest() { double Principal, Amount, IntRate, Period; int TypeOfPeriod; double Periods; string PeriodName; cout << "\nWe will calculate the interest rate applied on a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); Principal = LoanProcessing::GetPrincipal(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); IntRate = Finance::Rate(Accessories::Subtraction, Amount, Principal, Period); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return; } if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n"; cout << "\nFuture Value: $" << Amount; cout << "\nPrincipal: $" << Principal; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n"; cout << "\nInterest on Loan: " << IntRate << "%"; cout << "\n==================================\n"; } } #endif // MainH 
#include <iostream> #include "Main.h" #include "Loan.h" using namespace std; using namespace Accessories; using namespace LoanProcessing; int main() { int TypeOfCalculation; cout << "This program allows you to perform estimations on loans\n"; TypeOfCalculation = SelectCalculationType(); switch(TypeOfCalculation) { case 1: ProcessInterestAmount(); break; case 2: ProcessRateOfInterest(); break; default: cout << "\nInvalid Selection\n"; } return 0; } 
#ifndef LoanH #define LoanH namespace Finance { typedef double (*Add)(double R, double T); typedef double (*Subtract)(double First, double Second); typedef double (*Multiply)(double First, double Second); typedef double (*Divide)(double First, double Second); double InterestAmount(double P, double r, double t); double Rate(double (*AP)(double A, double P), double a, double p, double t); double TotalLoanAmount(double P, double r, double t); double PrincipalAmount(double (*RT)(double a, double b), double R, double T, double A); double Period(double (*AP)(double A, double P), double (*PR)(double P, double R), double a, double p, double r); double Period(double (*AP)(double A, double P), double a, double p, double r); } #endif 
#include "Loan.h" #pragma package(smart_init) namespace Finance { // Interest = Principal * rate * time in years double InterestAmount(double P, double r, double t) { return P * (r / 100) * t; } // Amount  Principal // Interest rate of a loan =  // Principal * Period double Rate(double (*AP)(double A, double P), double a, double p, double t) { double AMinusP = (*AP)(a, p); double Pt = p * t; return (AMinusP / Pt) * 100; } // Amount = Principal(1 + Rate * Interest) double TotalLoanAmount(double P, double r, double t) { return P * (1 + ((r / 100) * t)); } // Amount // Principal =  // 1 + Rate * Period double PrincipalAmount(double (*RT)(double a, double b), double R, double T, double A) { double RateOnTime = (*RT)(R/100, T); return A / (1 + RateOnTime); } // Amount  Principal // Interest rate of a loan =  // Principal * Rate // The following function provides a very simplistic way to calculate the // length of time of a loan. In fact, there is no checking on the // periodic value (whether the value is in days, quarters, months, or // years, and there is no algorithm to check the value of the time double Period(double (*AP)(double A, double P), double (*PR)(double P, double R), double a, double p, double r) { double AMinusP = (*AP)(a, p); double PTimesR = (*PR)(p, r / 100); return AMinusP / PTimesR; } } 
#if !defined MainH #define MainH #include <iostream> #include "Loan.h" using namespace std; namespace Accessories { // Accessory Functions // This function adds two values double Addition(double Value1, double Value2) { return Value1 + Value2; } // This function takes two arguments. // It subtracts the second from the first double Subtraction(double Value1, double Value2) { return Value1  Value2; } // This function multiplies two numbers double Multiplication(double Value1, double Value2) { return Value1 * Value2; } // This function takes two arguments // If the second argument is 0, the function returns 0 // Otherwise, the first argument is divided by the second double Division(double Numerator, double Denominator) { if( Denominator == 0 ) return 0; // else is implied return Numerator / Denominator; } } // namespace Accessories namespace LoanProcessing { double GetAmount() { double A; cout << "Enter the future value: $"; cin >> A; return A; } double GetPrincipal() { double P; cout << "Enter the Principal: $"; cin >> P; return P; } double GetInterestRate() { double r; cout << "Enter the Interest Rate (%): "; cin >> r; return r; } double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1  In Days"; cout << "\n2  In Months"; cout << "\n3  In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod; if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return static_cast<double>(Periods / 360); } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return static_cast<double>(Periods / 12); } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return static_cast<double>(Periods); } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; return 0.00; } } int SelectCalculationType() { int Answer; cout << "What kind of value do you want to estimate?"; cout << "\n1  Calculate (only) the interest paid on the loan"; cout << "\n2  Calculate the total amount owed on a loan"; cout << "\n3  Estimate the interest rate applied on a loan"; cout << "\n4  Find the amount given as loan"; cout << "\n5  Find the approximate length of time of a loan"; cout << "\nYour choice: "; cin >> Answer; return Answer; } void ProcessInterestAmount(bool GetTotalAmount = false) { double Principal, Amount, IntRate, Period, InterestAmount; int TypeOfPeriod; double Periods; string PeriodName; cout << "\n====================================================="; cout << "\nWe will calculate the interest amount payed on a loan\n"; cout << "\n====================================================="; cout << "\nLoan Processing\n"; Principal = LoanProcessing::GetPrincipal(); IntRate = LoanProcessing::GetInterestRate(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, get out of the function cout << "\nThe program will stop"; return; } InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); Amount = Finance::TotalLoanAmount(Principal, IntRate, Period); if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n"; cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: " << IntRate << "%"; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n"; cout << "\nInterest paid on Loan: $" << InterestAmount; if( GetTotalAmount == true ) cout << "\nTotal Amount Paid: $" << Amount; cout << "\n==================================\n"; } void ProcessRateOfInterest() { double Principal, Amount, IntRate, Period; int TypeOfPeriod; double Periods; string PeriodName; cout << "\n====================================================="; cout << "\nWe will calculate the interest rate applied on a loan\n"; cout << "\n====================================================="; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); Principal = LoanProcessing::GetPrincipal(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, get out of the function cout << "\nThe program will stop"; return; } IntRate = Finance::Rate(Accessories::Subtraction, Amount, Principal, Period); if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n"; cout << "\nFuture Value: $" << Amount; cout << "\nPrincipal: $" << Principal; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n"; cout << "\nInterest on Loan: " << IntRate << "%"; cout << "\n==================================\n"; } void ProcessPrincipal() { double Principal, Amount, IntRate, Period; int TypeOfPeriod; double Periods; string PeriodName; cout << "\n=================================================="; cout << "\nWe will calculate the principal value of the loan"; cout << "\n=================================================="; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); IntRate = LoanProcessing::GetInterestRate(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, get out of the function cout << "\nThe program will stop"; return; } Principal = Finance::PrincipalAmount(Accessories::Multiplication, IntRate, Period, Amount); if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n"; cout << "\nFuture Value: $" << Amount; cout << "\nInterest on Loan: " << IntRate << "%"; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n"; cout << "\nPrincipal: $" << Principal; cout << "\n==================================\n"; } void ProcessPeriod() { double Principal, Amount, IntRate, TimeSpan; int TypeOfPeriod; double Periods; string PeriodName; cout << "\n====================================================="; cout << "\nWe will calculate the amount of time to pay a loan\n"; cout << "\n====================================================="; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); Principal = LoanProcessing::GetPrincipal(); IntRate = LoanProcessing::GetInterestRate(); TimeSpan = Finance::Period(Accessories::Subtraction, Accessories::Multiplication, Amount, Principal, IntRate); cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n"; cout << "\nFuture Value: $" << Amount; cout << "\nPrincipal: $" << Principal; cout << "\nInterest on Loan: " << IntRate << "%"; cout << "\n"; cout << "\nPeriod: " << TimeSpan * 12 << " Months"; cout << "\n==================================\n"; } } #endif // MainH 
#include <iostream> #include "Main.h" #include "Loan.h" using namespace std; using namespace Accessories; using namespace LoanProcessing; int main() { int TypeOfCalculation; cout << "This program allows you to perform estimations on loans\n"; TypeOfCalculation = SelectCalculationType(); switch(TypeOfCalculation) { case 1: ProcessInterestAmount(); break; case 2: ProcessInterestAmount(true); break; case 3: ProcessRateOfInterest(); break; case 4: ProcessPrincipal(); break; case 5: ProcessPeriod(); break; default: cout << "\nInvalid Selection\n"; } return 0; } 
This program allows you to perform estimations on loans What kind of value do you want to estimate? 1  Calculate (only) the interest paid on the loan 2  Calculate the total amount owed on a loan 3  Estimate the interest rate applied on a loan 4  Find the amount given as loan 5  Find the approximate length of time of a loan Your choice: 5 ===================================================== We will calculate the amount of time to pay a loan ===================================================== Loan Processing Enter the future value: $824 Enter the Principal: $800 Enter the Interest Rate (%): 9 ================================== Estimate on loan  Future Value: $824 Principal: $800 Interest on Loan: 9%  Period: 4 Months ================================== Press any key to continue... 
An Array of (Pointers to) Functions 
To further refine the call to a group of functions that perform the same kind of task, you can declare an array of pointers to a type of function. Before creating an array of pointers to function, you must first know or have the functions you would be referring to. These functions must have a similar signature. This means that they must return the same type of value, they must have the same number of arguments and they must have the same type(s) of argument(s). Here are examples of such functions: 
double Diameter(double Radius) { return Radius * 2; } double Circumference(double Radius) { return Diameter(Radius) * PI; } double Area(double Radius) { return Radius * Radius * PI; }
To declare an array of pointers to function, you can first define an alias to the variable. This is an example: typedef double (*Measure)(double R); After this definition, as we learned already, Measure is an alias to a function that takes a double type of variable and returns a double value. Using this name, you can declare an array of functions. The members of the array are names of the functions that would compose the array. Here is an example: Measure Calc[] = { Diameter, Circumference, Area }; You can initialize each member using its index and calling the corresponding function. This can be done as follows: 
#include <iostream> using namespace std; const double PI = 3.14159; double Diameter(double Radius) { return Radius * 2; } double Circumference(double Radius) { return Diameter(Radius) * PI; } double Area(double Radius) { return Radius * Radius * PI; } int main() { typedef double (*Measure)(double R); double R = 12.55; Measure Calc[] = { Diameter, Circumference, Area }; double D = Calc[0](R); double C = Calc[1](R); double A = Calc[2](R); cout << "Circle Characteristics"; cout << "\nDiameter: " << D; cout << "\nCircumference: " << C; cout << "\nArea: " << A << endl; return 0; }
This would produce:
Circle Characteristics Diameter: 25.1 Circumference: 78.8539 Area: 494.808 Press any key to continue...
Practical Learning: Using an Array of Functions 
#include <iostream> using namespace std; typedef char (*Question)(); enum TMCQuestion { One, Two, Three, Four, Five }; char Sequence() { char Answer; cout << "Which sequence of numbers does not appear to follow " << "a recognizable order?"; cout << "\n(a) 3 9 27 33"; cout << "\n(b) 3 6 9 12"; cout << "\n(c) 2 4 6 8"; cout << "\n(d) 102 204 408 816"; cout << "\nAnswer: "; cin >> Answer; return Answer; } char Expression() { char Response; cout << "Select the best expression to complete the empty space"; cout << "\nWhen ... drugs to a business address, traffickers often " << "omit a recipient name"; cout << "\n(a) to send"; cout << "\n(b) senders"; cout << "\n(c) sending"; cout << "\n(d) dealing"; cout << "\nAnswer: "; cin >> Response; return Response; } char Sentence() { char Answer; cout << "Even ... there are 76,000 lawyers in that city, it is still " << "a small community"; cout << "\n(a) although"; cout << "\n(b) though"; cout << "\n(c) for"; cout << "\n(d) since"; cout << "\nAnswer: "; cin >> Answer; return Answer; } char WrongWord() { char Wrong; cout << "Select the wrong word that would complete the sentence"; cout << "\nFor this type of business, revenue gains are ..."; cout << "\n(a) limited"; cout << "\n(b) scarce"; cout << "\n(c) limitless"; cout << "\n(d) claiming"; cout << "\nAnswer: "; cin >> Wrong; return Wrong; } char Right() { char Sentence; cout << "Select the right sentence"; cout << "\n(a) The company is expecting to reducing inventory," << "\n control cost, and efficiency improvement."; cout << "\n(b) The company expects to reduce inventory," << "\n control cost, and improve efficiency."; cout << "\n(c) The company expects to reduce inventory," << "\n control cost, and improving efficiency."; cout << "\n(d) The company is expecting to reducing inventory," << "\n controlling cost, and efficiency improvement."; cout << "\nAnswer: "; cin >> Sentence; return Sentence; } void ValidateAnswer(const int QstNbr, const char Ans); int main() { const int NumberOfQuestions = 5; char ValidAnswer; char Answer[NumberOfQuestions]; Question MCQ[] = { Sequence, Expression, Sentence, WrongWord, Right}; for(int i = 0; i < NumberOfQuestions; i++) { cout << "Question " << i + 1 << endl; Answer[i] = MCQ[i](); ValidateAnswer(i+1, Answer[i]); cout << "\n\nPress any key to continue..."; clrscr(); } return 0; } void ValidateAnswer(const int QstNbr, const char Ans) { switch(QstNbr) { case 1: if(Ans == 'a'  Ans == 'A') cout << "Right Answer"; else { cout << "Wrong Answer  The right answer was 'a'"; cout << "\n(a) Starting at 3, 3*3=9 and 3*9=27"; cout << "\n There is no obvious way to determine 33"; } break; case 2: if(Ans == 'c'  Ans == 'C') cout << "Right answer"; else cout << "Wrong Answer  The right answer was 'c'"; break; case 3: if(Ans == 'b'  Ans == 'B') cout << "Right answer"; else cout << "Wrong Answer  The right answer was 'b'"; break; case 4: if(Ans == 'd'  Ans == 'D') cout << "Right answer"; else cout << "Wrong Answer  The right answer was 'd'"; break; case 5: if(Ans == 'b'  Ans == 'B') cout << "Right answer"; else cout << "Wrong Answer  The right answer was 'b'"; break; default: cout << "Invalid Answer"; } } 


Previous  Copyright © 2008 Yevol  Next 
