Function Address

Suppose it is necessary to assign the address of an overloaded function to a pointer. The address of the exact version of the function will be retrieved by matching the function with the pointer declaration. Consider the following two versions of the overloaded print() function:
void print(char c)
{
     cout << c << endl;
}

void print(int i)
{
     cout << i << endl;
}
If two function pointers are declared:
void (*pchar)(char x);
void (*pint) (int y);
and an attempt is made to assign the address of print() to pchar, the version of print() taking a char as an argument will be selected by the compiler, as it matches pchar’s definition. In case pint were chosen, the address of the int version of print() would be assigned.

Example


#include <iostream>
using namespace std;

void print(char c)
{
     cout << c << endl;
}

void print(int i)
{
     cout << i << endl;
}

int main()
{   
     void (*pchar)(char x);
     void (*pint) (int y);
     pchar = print;         // the char version is assigned
     pchar('d');            
     pint = print;          // the int version is assigned
     pint(56);   
}

Output

d
56