The two have very different uses.
The void*
serves primarily to pass a pointer, for any type, in a function, or to save a pointer for anything. Once a value is assigned, it can be replaced by another of any kind. There is a serious problem: you lose the information about the original type. When it comes to reading what you have in a void*
it is necessary to make a cast, and if you don’t do it correctly the program will crash. In C it is essential, but in C++ there are several safer alternatives, such as class hierarchies or templates. It is also very interesting boost:any., that will eventually enter the standard some day. And is also gaining strength lately the concept of type Erasure, where you can create a type that accepts object assignment of any other type, without explicit relation, provided that they respond to a bounded set of commands, such as the ++ operator or a specific function. There’s a very good explanation here about that.
Already the auto
, from C++11 serves to declare variables whose type will be inferred by the compiler from their initialization. Cannot be used for parameter or as a member of a class. Once assigned a value for a variable auto
, it is impossible to change the type of the variable, after all auto
serves only to say to the compiler: "I do not want to write the type of the variable, but I want it to be the type of what I am assigning". There is a certain controversy when using it because it can lead to the creation of obfuscated code. An interesting use of it, however, is to minimize the verbosity of the code, especially in the use of iterators and related, for example:
for (std::map<std::string,std::string>::iterator iter = map.begin(); iter != map.end(); ++iter) { ... }
versus
for (auto iter = map.begin(); iter != map.end(); ++iter) { ... }
The second option is less obvious, but to be absolutely sure of the type of iter
you have to know the type of map
and the return of function begin()
.
In short, void*
is a legacy solution for generic programming. The auto
is a code simplifier, which does not replace the void*
, although there are other modern alternatives to it, as I mentioned above.
Would that be equivalent to
var
ofC#
?– Conrad Clark
Yeah, from what I understand it seems to have the same var functionality in C#.
– E.Thomas
I can’t say because I know very superficially C#, but if the
var
is to declare variables where their type is inferred by the compiler from the expression used at their initialization, must be equivalent yes.– C. E. Gesser