What Does '&' Do in a C++ Declaration

What does '&' do in a C++ declaration?

The "&" denotes a reference instead of a pointer to an object (In your case a constant reference).

The advantage of having a function such as

foo(string const& myname) 

over

foo(string const* myname)

is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Since you are passing by reference, the object is not copied, just like if you were passing a pointer.

Your second example:

const string &GetMethodName() { ... }

Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access:

class A
{
public:
int bar() const {return someValue;}
//Big, expensive to copy class
}

class B
{
public:
A const& getA() { return mA;}
private:
A mA;
}
void someFunction()
{
B b = B();
//Access A, ability to call const functions on A
//No need to check for null, since reference is guaranteed to be valid.
int value = b.getA().bar();
}

You have to of course be careful to not return invalid references.
Compilers will happily compile the following (depending on your warning level and how you treat warnings)

int const& foo() 
{
int a;

//This is very bad, returning reference to something on the stack. This will
//crash at runtime.
return a;
}

Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.

What does `*&` in a function declaration mean?

The & symbol in a C++ variable declaration means it's a reference.

It happens to be a reference to a pointer, which explains the semantics you're seeing; the called function can change the pointer in the calling context, since it has a reference to it.

So, to reiterate, the "operative symbol" here is not *&, that combination in itself doesn't mean a whole lot. The * is part of the type myStruct *, i.e. "pointer to myStruct", and the & makes it a reference, so you'd read it as "out is a reference to a pointer to myStruct".

The original programmer could have helped, in my opinion, by writing it as:

void myFunc(myStruct * &out)

or even (not my personal style, but of course still valid):

void myFunc(myStruct* &out)

Of course, there are many other opinions about style. :)

What's the meaning of * and & when applied to variable names?

The unary prefix operator &, when applied to an object, yields the address of the object: &obj.

The type modifier &, when applied to a variable about to be declared, will modify the variable's type to be a reference type: int&.

The same applies to *: When applied as a unary prefix operator to a pointer, it will dereference the pointer, yielding the object referred to: *ptr.

When used as a type modifier to a variable about to be declared, * will modify the type to be a pointer: int*.

In a similar way, the type modifier [] applied to a variable that's being declared will modify the variable's type to an array, while the binary infix operator [] applied to an object of array type will access one of the array's sub-objects.


It's not helpful that type modifiers apply to the variable that is declared, not to the type they are declared with. For example, this

int *p, **pp, i, a[10], &r = i; 

defines an int pointer, a pointer to a pointer to an int, a vanilla int, an array of 10 int, and an int reference. (The latter is immediately initialized, because you cannot have an uninitialized reference.) Note that the type modifiers syntactically belong to the declared variable whose type they are modifying, not to the declared variable's type. Nevertheless, type modifiers (* and &) modify the type of the variable.

In the following case, however, with p, i, and a presumed to be variables that have already been declared

*pp = &i;
a[0] = i;

* and & are unary prefix operators dereferencing pp and yielding the address of i, while [] yields the first int object in the array a.

The fact that C and C++ don't care about the whitespaces around type modifiers and that this led to different camps when it comes to place them doesn't really make things easier.

Some people place the type modifiers close to the type. They argue that it modifies the type and so it should go there:

int* ptr;

The disadvantage is that this becomes confusing when declaring several objects. This

int* a, b;

defines a to be a pointer to int, but b to be an int. Which is why some people prefer to write

int *ptr;
int *a, *b;

I suggest to simply never declare multiple objects in the same statement. IMO that makes code easier to read. Also, it leaves you free to pick either convention.


To complicate things even further, besides the type modifiers and the unary prefix operators & and *, there are also the binary infix operators & and *, meaning "bitwise AND" and "multiplication". And to add insult to injury, in C++ you can overload both the unary prefix and the binary infix variants of these operators (and the binary infix []) for user-defined types and be completely free as to their semantics.

Meaning of *& and **& in C++

That is taking the parameter by reference. So in the first case you are taking a pointer parameter by reference so whatever modification you do to the value of the pointer is reflected outside the function. Second is the simlilar to first one with the only difference being that it is a double pointer. See this example:

void pass_by_value(int* p)
{
//Allocate memory for int and store the address in p
p = new int;
}

void pass_by_reference(int*& p)
{
p = new int;
}

int main()
{
int* p1 = NULL;
int* p2 = NULL;

pass_by_value(p1); //p1 will still be NULL after this call
pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory

return 0;
}

Use of '&' operator before a function name in C++

In C++, when the ref-sign (&) is used before the function name in the declaration of a function it is associated with the return value of the function and means that the function will return by reference.

int& foo(); // Function will return an int by reference.

When not used within a declaration context, putting the ref-sign before a function name results in calling the address-of operator returning the address of the function. This can be used to e.g. create a pointer to a function.

// Some function.
int sum(int a, int b) {
return a + b;
}

int main() {
// Declare type func_ptr_t as pointer to function of type int(int, int).
using func_ptr_t = std::add_pointer<int(int, int)>::type;

func_ptr_t func = ∑ // Declare func as pointer to sum using address-of.
int sum = func(1, 2); // Initialize variable sum with return value of func.
}

In C, the only use of & is for the address-of operator. References does not exist in the C language.

how does the ampersand(&) sign work in c++?

To start, note that

this

is a special pointer ( == memory address) to the class its in.
First, an object is instantiated:

CDummy a;

Next, a pointer is instantiated:

CDummy *b;

Next, the memory address of a is assigned to the pointer b:

b = &a;

Next, the method CDummy::isitme(CDummy ¶m) is called:

b->isitme(a);

A test is evaluated inside this method:

if (¶m == this) // do something

Here's the tricky part. param is an object of type CDummy, but ¶m is the memory address of param. So the memory address of param is tested against another memory address called "this". If you copy the memory address of the object this method is called from into the argument of this method, this will result in true.

This kind of evaluation is usually done when overloading the copy constructor

MyClass& MyClass::operator=(const MyClass &other) {
// if a programmer tries to copy the same object into itself, protect
// from this behavior via this route
if (&other == this) return *this;
else {
// otherwise truly copy other into this
}
}

Also note the usage of *this, where this is being dereferenced. That is, instead of returning the memory address, return the object located at that memory address.



Related Topics



Leave a reply



Submit