Function Pointers

Function pointers are working basically same way as the normal pointers. Difference is that you can point to a function. Pointed functions can be called through the pointers of course. In this tutorial section we are going to do exactly that. Let’s get started with basic Function pointer.


Function Pointer

First, Let’s create a C++ class based on actor. We Create two functions called MyFunction and MyFunction2. In Declaration we do some printing.

void APuzzleProjectCGameMode::MyFunction()
{
  UE_LOG(LogTemp, Warning, TEXT("MyFunc Run"));

}

void APuzzleProjectCGameMode::MyFunction2()
{
  UE_LOG(LogTemp, Warning, TEXT("MyFunc2 Run"));
}

Back in the header file, let’s create a function pointer. It doesn’t take any parameters and it returns void.

// We need to help compiler little bit. We manyally define the function, so we can create a object out of it.
typedef void (APuzzleProjectCGameMode::*FunctionPointer)(void);
FunctionPointer MyFunctionPointer;

Inside .CPP we can point to any function we like.

MyFunctionPointer = &APuzzleProjectCGameMode::MyFunction;

Now that we have a variable that points to a function, we can pass it to anywhere and whenever we wan’t to call it we type

// We give object name that calls the function. OurSelf.
(this->*MyFunctionPointer)();

That’s all you need to do. If we wan’t to make this more interesting, we can create an array of function pointers and call them through array! In Header file let’s define another function pointer, but array this time.

typedef void (APuzzleProjectCGameMode::*ArrayOfFunctionPointers)(void);
  ArrayOfFunctionPointers MyFunctions[2];

In .CPP we can set them

MyFunctions[0] = &APuzzleProjectCGameMode::MyFunction;
  MyFunctions[1] = &APuzzleProjectCGameMode::MyFunction2;

Now, if we like, we can call in in loop for example!

for (int i = 0; i < 2; i++)
  {
    (this->*MyFunctions[i])();
  }

That’s it! Now you know how to successfully create a function pointer


 Extra note! If you wan’t to pass a function as parameter, you can easily achieve that through the delegates. You can pass delegate to any class and when you call the delegate, no matter where it was binded, it will run normally! Just remember to #include the class that originally created the delegate or it doesn’t recognize it!

Vastaa

Sähköpostiosoitettasi ei julkaista. Pakolliset kentät on merkitty *