C++ Void pointers-everything you need to know

Here we will see everything about void pointers,how to declare it and how to access them and also how to use them in our programs.

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,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,

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 ; 

The output is,

90

We can use void pointer to and make it behave like any normal pointer but in order to access the value pointed by the void pointer we must sure that the pointer is casted to the correct type first.Therefore,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 

The output value of st here is undefine,it can be anything.