amanuel2 amanuel2 - 1 year ago 86
C++ Question

Difference between Auto and Void?

I am reading the C++ Primer Book (fifth edition) and I have a question upon the book i am reading. It says:

The type
is a special pointer type that can hold the address of
any object. Like any other pointer, a
pointer holds an address,
but the type of the object at that address is unknown.

Ok, so I understand that but… I have many contradictions to the statement. First of all, can't you use
? Doesn't it do the same thing as
? Meaning aren't

void *somePtr;


auto *somePtr;

the same?

Second of all it says the type of the attached address is unknown. Can't you use
to get the type? Like this:

int a = 5;
auto *somePtr = 5;
std::cout << typeid(*somePtr).name() << std::endl;

Answer Source

Did you try running your examples through a compiler? As it happens, neither

auto * p;  // error


int a = 0;
void * p = &a;
std::cout << typeid(*p) << '\n';  // error

will compile while both

void * p;


int a = 0;
auto * p = &a;
std::cout << typeid(*p) << '\n';

are fine.

To give an informal and easy to remember analogy for void * and auto *, think of void * p as telling the compiler

Don't care about what p pointer points to, I'll handle it myself (at run-time).

whereas auto * p = (expression) tells the compiler

Please figure out for me (at compile-time) what (pointer) type (expression) evaluates to and make the type of p be accordingly.

As a matter of fact, auto * is rarely useful. You can simply write auto instead and if the initializing expression is a pointer type, the auto will be deduced to be a pointer, too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download