Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void pointers in C++

Tags:

c++

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!

like image 905
w4j3d Avatar asked Nov 29 '10 15:11

w4j3d


1 Answers

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.

like image 155
James McNellis Avatar answered Sep 28 '22 05:09

James McNellis