Skip to content

Instantly share code, notes, and snippets.

@AndiH
Created July 2, 2013 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AndiH/5909069 to your computer and use it in GitHub Desktop.
Save AndiH/5909069 to your computer and use it in GitHub Desktop.
HOW TO example: Function pointers, external / internal [C++]
/*
Demonstration of how to use function pointers in classes.
First off, a class called operationClass is defined. This can as well be extracted to a single operationClass.h file. It's included in this cpp file to give a short overview.
operationClass is calle by the subsequent main().
opreationClass provides a method to set its internal calculation function to squaring and one to cubing. It also provides a method to call giving an external calculation function. The three examples are given in main().
Andreas Herten, 2.7.2013
*/
#include <iostream>
struct operationClass {
void SetSquare() { fPrintFunc = square;};
void SetCube() { fPrintFunc = cube;};
void SetArbitrary(int (*func)(int)) { fPrintFunc = func;};
int returnTransformedValue(int val) {return fPrintFunc(val);};
private:
int (*fPrintFunc)(int);
static int square(int val) {return val*val;}; // has to be static!
static int cube(int val) {return val*val*val;};
};
int quad(int number) {
return number * number * number * number;
}
int main() {
int originalValue = 5;
operationClass * myClass = new operationClass();
myClass->SetSquare();
std::cout << originalValue << " squared (with in-class square function) = " << myClass->returnTransformedValue(originalValue) << std::endl;
myClass->SetCube();
std::cout << originalValue << " cubed (with in-class square function) = " << myClass->returnTransformedValue(originalValue) << std::endl;
// int quadrupled = myClass->returnArbitrary(originalValue,quad);
myClass->SetArbitrary(quad);
std::cout << originalValue << " quadrupled (with external quad function) = " << myClass->returnTransformedValue(originalValue) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment