Void Pointer

Void pointers do not have any data type of their own and can therefore be assigned to point to ANY other data type.

 

Represents just the address of an object but not its data type.

 

CANNOT be dereferenced directly - HAS to be typecast to the data type of the object being pointed to

 

#include <iostream>
using namespace std;

int main () {

	int myInt = 12 ;
	int *ptrInt;
	float myFlt = 14.6345;
	float *ptrFlt;

	void *vPtr ;              	//declare a void pointer

	vPtr = &myInt ;           	//assign address of myInt to void pointer

								//assign void pointer to int pointer
	ptrInt = (int *)vPtr ;      //explicit cast (only in C++, not c)

	cout << "value: " << *ptrInt << endl ;

	vPtr = &myFlt ;             //assign address of myFlt to void pointer

								//assign void pointer to float pointer
	ptrFlt = (float *)vPtr ;    //explicit cast (only in C++, not c)

	cout << "value: " << *ptrFlt << endl ;
	cout << "value: " << *(float *)ptrFlt << endl ;

	return 0;
}

Compile & Run:

value: 12
value: 14.6345
value: 14.6345

 

 

*Note: Unlike C, you cannot implicitly cast from void * in C++. In C++ it must be explicitly cast

 

source

Leave a Reply