Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On C++ pointers and references, clarification needed

What of the below is wrong please?

It is my understanding that a pointer represents an address of something of some type.

So, int i = 18, a pointer to it is int *pI = &i;

The following 2 declarations are valid

void foo (int &something) // Will accept an address of something
void bar (int *something) // Will accept a pointer to something

When we declare a function as

void bar (int *something)

We better send a pointer to something. Indeed, foo(pI) works.

Following the same logic, when looking at

void foo (int &something)

We should send it an address of something pointing to an int as an argument, so then:

Why is foo(&i) wrong?

like image 651
James Raitsev Avatar asked Aug 07 '12 01:08

James Raitsev


1 Answers

void foo (int &something) // Will accept an address of something

This is incorrect: int& is a reference, a concept that is similar to pointers in certain ways, but not at all identical.

References are similar to pointers in that a value can be changed through a reference, just like it can be changed through a pointer. However, there is no such thing as "null reference", while NULL pointers are very common.

When you call a function that takes a reference, you simply pass the variable the reference to which you are taking - no & operator is required:

void foo (something); // "something" must be a variable
like image 126
Sergey Kalinichenko Avatar answered Sep 20 '22 10:09

Sergey Kalinichenko