Like pointers in C ( *int , *char ) we can use pointers to a function .
Here's a sample of Function Pointer ::
#include "iostream"
void Sample(){
std::cout << " This is sample function call ." << std::endl;
};
int main(){
auto function = Sample;
function();
function();
};
We can use it as ::
void Sample(){
std::cout << " This is sample function call ." << std::endl;
};
int main(){
void(*function)();
function = Sample;
function();
function();
};
Using typedef in function pointers ::
void Sample(){
std::cout << " This is sample function call ." << std::endl;
};
int main(){
typedef void(*Function)();
Function function = Sample;
function();
function();
};
Passing a Function as a Parameter to another function to call it ::
#include "iostream"
#include "vector"
void PrintValue(int value){
std::cout << "The Value got is : " << value << std::endl;
};
void ForEach(const std::vector<int>& values , void(*function)(int)){
for(auto i : values){
function(i);
};
};
int main(){
std::vector<int> sample_vector = {1,2,4,3,5,7};
ForEach(sample_vector,PrintValue);
};