Function Pointers or Delegates

#Wiki Tutorial on Function Pointers

I wrote an entire tutorial on Function Pointers!

Enjoy!

#:heart:

Rama

#The Code, not as pretty as on wiki

#include "YourClass.generated.h"
 
#define BEHAVIORS_MAX 30
 
UCLASS()
class AYourClass : AActor //or any other class setup
{
	GENERATED_UCLASS_BODY()
 
public:
 
	//The Function Pointer Variable Type
	//Functions take in 0 parameters and return void
	typedef void (AYourClass::*FunctionPtrType)(void);
 
	//A static array of 30 Function Pointers
	FunctionPtrType BehaviorFunctions[BEHAVIORS_MAX];
 
	//Play a Behavior from the Function Pointer Array
	//	implementation does not vary in subclasses, so not virtual
	void PlayBehavior(int32 BehaviorIndex );
 
	//Initialize the array
	void InitBehaviors();
 
	//The actual functions which are implemented in subclasses
	//or this class itself
	virtual void PlayBehavior_Idle_LookLeftToRight();
	virtual void PlayBehavior_Idle_LookFullCircle();
	virtual void PlayBehavior_Idle_ScanUpDown();
	//...more functions


.cpp




#define LOOK_FULL_CIRCLE 0
 
#define SCAN_LEFT_TO_RIGHT 1
 
#define SCAN_UP_DOWN	  2
//... more function index defines to 29
 
void AYourClass::InitBehaviors()
{
	BehaviorFunctions[LOOK_FULL_CIRCLE] = &AYourClass::PlayBehavior_Idle_LookFullCircle;
	BehaviorFunctions[SCAN_LEFT_TO_RIGHT] = &AYourClass::PlayBehavior_Idle_LookLeftToRight;
	BehaviorFunctions[SCAN_UP_DOWN] = &AYourClass::PlayBehavior_Idle_ScanUpDown;
	//...more functions
}
 
void AYourClass::PlayBehavior_Idle_LookLeftToRight(){}
void AYourClass::PlayBehavior_Idle_LookFullCircle(){}
void AYourClass::PlayBehavior_Idle_ScanUpDown(){}
//...rest of functions
 
 
void AYourClass::PlayBehavior(int32 BehaviorIndex )
{
	//valid range check
	if (BehaviorIndex >= BEHAVIORS_MAX || BehaviorIndex < 0) return;
	//~~
 
	//Special Thanks to Epic for this Syntax
	(this->* (BehaviorFunctions[BehaviorIndex]))();
 
	//the above line plays the appropriate function based on the passed in index!
}