Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are void pointers for in C++?

Tags:

c++

pointers

My question is simple: What are void pointers for in C++? (Those things you declare with void* myptr;)

What is their use? Can I make them point to a variable of any type?

like image 383
Dr. Acula Avatar asked May 18 '10 19:05

Dr. Acula


5 Answers

Basically, a remnant from C.

What is their use?

In C, they were and are used widely, but in C++ I think they are very rarely, if ever, needed, since we have polymorphism, templates etc. which provide a much cleaner and safer way to solve the same problems where in C one would use void pointers.

Can I make them point to a variable of any type?

Yes. However, as others have pointed out, you can't use a void pointer directly - you have to cast it into a pointer to a concrete data type first.

like image 126
Péter Török Avatar answered Sep 20 '22 04:09

Péter Török


Yes, this is a C construct (not C++-specific) that allows you to declare a pointer variable that points to any type. You can't really do much of anything with such a pointer except cast it back to the real object that it actually points to. In modern C++, void* has pretty much gone out of fashion, yielding in many cases to template-based generic code.

like image 44
jwismar Avatar answered Sep 22 '22 04:09

jwismar


About one of the few uses that exist for void pointers in C++ is their use in overloading the new operators. All new operators return type void* by definition. Other than that, what others have said is true.

like image 42
wheaties Avatar answered Sep 20 '22 04:09

wheaties


From cplusplus.com:

The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties).

This allows void pointers to point to any data type, from an integer value or a float to a string of characters. But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.

like image 41
Raul Agrait Avatar answered Sep 24 '22 04:09

Raul Agrait


Type hiding. It does still have its valid uses in modern C++. Dig through the source code in boost and you'll find a few. Generally the use of a void* is buried very deep within the bowels of a more complex construct that ensures the type safety of the interface while doing black and evil magic within.

like image 35
Edward Strange Avatar answered Sep 23 '22 04:09

Edward Strange