In this article, I wanted to revised a little bit on how functions pointers works in C++. You can think of pointers as variable that points to memory address of other variables, but let’s use them to point to functions. In C++, you can make a pointer point to a function! Function being a block of code we execute when we call it, but how about having pointers to them!

What is a function

Quite basic overview, but let’s review some basics on functions:

#include <iostream>

void PrintNumber(int number)
{
	std::cout << number;
}

int main()
{
	PrintNumber(12);
}

The output would be 12, or any number we pass in the call of the function!

We cann pass a pointer to a variable in Main() to change the value into the function scope. Let’s assume this:

#include <iostream>

void PrintNumber(int* number)
{
	std::cout << *number;
}

int main()
{
	int a = 12;
	int* pointerToA = &a;
	PrintNumber(pointerToA);
}

We declare a int variable with name a, and then we assign the memory pointer with int* pointerToA = &a;

Our function signature now takes a pointer to where a variable lives in memory. So we need to pass the pointer to something to use that function, this is what we do in this line:

PrintNumber(pointerToA);

If we run the code: we have this:

Leave a Reply

Your email address will not be published. Required fields are marked *