C++ Void pointers function

In C and C++ ‘void‘ means no type and so we cannot use void as a data type or declare a variable of void type.

void vd=90 ; ///error

Since void means no type it there is no literals of such type.This makes void type as a suitable return type when no value is return by the function.For instance,

Link: Literals

void func() //func() returns no type or nothing
cout << “This function returns nothing” ;
return ; /* return nothing or you can also remove this return ; statement t will mean the same*/

int main( )
func( ) ;

cin.get() ;
return 0 ;

This is one of the uses of void type-suitable for return type when no value is returned-in C++.

void pointer

There is an exception to the use of void as a type.Although declaring a variable for a void is not allowed we can declare a pointers of a void type.

void *vdp ;   ///Works fine
void rd ;   ///Error

The advantage of using void pointer is that a void pointer can point to the address of any data type.But we cannot access the value which it points to.

int i=90 ;
void *ip ;
ip=&i ;   ///Works fine
cout<< *ip ;   /* error:cannot access the value of i */

Accessing void pointer

If we want to access the value of another variable which the void pointer points to then we have to cast the void pointer to that type.

int i=90 ;
void *ip=&i ;
int *iv=static_cast<int *>(ip) ; ///Casting ip to int type
cout<< *iv ;

So ,the disadvantage of using void pointer is that we have to know the exact data type of the variable to cast it.Beware! if we cast the void pointer to some other type it will introduce a bug in your code.

string st=*static_cast<string *>(ip) ;// casting to string type

cout<< st ; //undefined