#include <iostream>
usingnamespace std;
void increase (void* data, int psize) // data is a void pointer that can point to objects of any type.
{
if ( psize == sizeof(char) ) // if the input psize matches size of char
{
char* pchar; // pchar is a pointer to char
pchar=(char*)data; // make data a pointer to char (explicit casting) and make pchar also point to the same data.
++(*pchar); // increase the value that is pointed to by pchar
}
elseif (psize == sizeof(int) ) // if the input psize matches size of int
{
int* pint; // pint is a pointer to int
pint=(int*)data; // make data a pointer to int (explicit casting) and make pint also point to the same data.
++(*pint); // increase the value that is pointed to by pint
}
}
int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a)); // increase a char
increase (&b,sizeof(b)); // increase an int by the same function
cout << a << ", " << b << endl;
return 0;
}
The part to the right of the assignment operator, (char*)data, is called a "type cast". What this is doing is telling the program to treat the variable, data, as a pointer to a char regardless of what it actually is.
EDIT: Note that it does not actually change the data type of 'data'. Any other time you address this variable in the code it will be a void pointer unless you cast it again.