I saw this example on a website, and the websites mentions:- "One of its uses (void pointers) may be to pass generic parameters to a function"
// increaser
#include <iostream>
using namespace std;
void increase (void* data, int psize)
{
if ( psize == sizeof(char) )
{ char* pchar; pchar=(char*)data; ++(*pchar); }
else if (psize == sizeof(int) )
{ int* pint; pint=(int*)data; ++(*pint); }
}
int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
return 0;
}
wouldn't it be simpler to write code like the following?
void increaseChar (char* charData)
{
++(*charData);
}
void increaseInt (int* intData)
{
++(*intData);
}
int main ()
{
char a = 'x';
int b = 1602;
increaseChar (&a);
increaseInt (&b);
cout << a << ", " << b << endl;
string str;
cin >> str;
return 0;
}
It is less code, and really straightforward. And in the first code I had to send the size of the data type here I don't!
It would be best to make the function type safe and generic. It would also be best to take the argument by reference instead of by pointer:
template <typename T>
void increment(T& data) {
++data;
}
void*
should be avoided wherever possible in C++, because templates and inheritance provide type-safe alternatives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With