Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address-of operator (&) vs reference operator(&)

Tags:

c++

I am kind confused about this case:

Declare a pointer:

int b =10;
int*a=&b;

Here & takes the address of b.

Consider another example:

/* Reference to the calling object can be returned */

Test& Test::func ()
{
   // Some processing
   return *this;
} 

this should be a pointer, *this is the obeject pointed. But here we are asking to assign *this to &Test.

What should we modify the code to let the function return the address. Should we still use Test& ?

like image 920
Weijia Avatar asked Feb 24 '16 05:02

Weijia


People also ask

Which is the address of operator in pointer?

The unary address-of operator ( & ) returns the address of (that is, a pointer to) its operand. The operand of the address-of operator can be a function designator or an lvalue that refers to an object that's not a bit field.

Why do we use address operator in C?

Address operator is used to storing the address of the variable in C. This is denoted by an ampersand (&). This is also used for scanning the user input.

What is address operator in C programming?

The & (address) operator yields a pointer to its operand. The operand must be an lvalue, a function designator, or a qualified name. It cannot be a bit field.

What is the value of address operator in C?

The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. The * is a unary operator which returns the value of object pointer by a pointer variable. It is known as value of operator.


1 Answers

In C++ there're two different syntax units:

&variable; // extracts address of variable

and

Type& ref = variable; // creates reference called ref to variable

Easy usage example:

int v = 5;

cout << v << endl; // prints 5
cout << &v << endl; // prints address of v

int* p;
p = &v; // stores address of v into p (p is a pointer to int)

int& r = v;

cout << r << endl; // prints 5

r = 6;

cout << r << endl; // prints 6
cout << v << endl; // prints 6 too because r is a reference to v

As for using references in functions, you should google "passing by reference in C++", there're many tutorials about it.

like image 193
Fomalhaut Avatar answered Sep 21 '22 07:09

Fomalhaut