okami
okami

Reputation: 2153

basic c++ pointer question

if I have a function like that:

void doSomething(int& aVar)
{
// do something
}

and I have this:

int *aVar = new int;
*aVar = 10;

doSomething(*aVar);

Why should I call *aVar? isn't aVar already an address?

Upvotes: 2

Views: 229

Answers (4)

Ed Swangren
Ed Swangren

Reputation: 124622

No, a reference is not a pointer. References are guaranteed to not be null; you cannot say the same for a pointer. When you pass an int to a function that expects an int& the reference will be taken automatically.

P.S. Don't think of it as an address or a fancy pointer. It is a reference, or an alias to an existing object.

Upvotes: 8

Kos
Kos

Reputation: 72221

The asterisk, besides multiplication has two meanings:

a) When declaring a variable: *x means "X is a pointer" b) When using a variable: *x (when x is of pointer type) means "take whatever is pointed by x" - the opposite of &x, which means "take the address of x".

The code:

doSomething(*aVar)

just wants to dereference the pointer "aVar" (take the value of type int pointed by it) and pass this value of type int as a parameter to the function.

The variable "aVar" stores an address of some integer value, not the value itself, so you have to use the "*" operator to dereference it every time you want to access the integer, not the memory address itself.

References in C++ are quite counter-intuitive ("disguised pointers"), so if doSomething takes a reference to int, you have to call it as if you were passing an actual int value, not a pointer. Hence you need the dereference operator.

Upvotes: 1

GWW
GWW

Reputation: 44093

A pointer is pointing to a specific memory address and a pointer has it's own data (ie the memory address it's pointing to). When you pass aVar to the function without dereferencing (the * operator) the pointer you would be passing the memory location of the pointer, not the memory location the pointer is pointing to.

Upvotes: 0

pm100
pm100

Reputation: 50110

doSomething(int&)

wants a reference not a pointer. The way to set up that reference as a parameter is to pass in an Int. Which is why

doSomething(*aVar)

works. If you want to use a pointer in the function say

doSomething(int*)

references and pointers are not the same thing (although they have a lot in common)

Upvotes: 2

Related Questions