What is the purpose of the symbol " & " in the declaration of an object?

I noticed that in some declarations of variables/objects you use * for the Declaration (thus generating a pointer), but in some cases you have the declaration using &.

const MyClass & my_class = object.getMyClass();

What is the " & " for when declaring an object?

Author: Maniero, 2020-12-23

1 answers

This symbol indicates that it is creating a reference instead of a pointer, but it works analogously (not equal).

It is part of the type and not the variable, let alone the object itself, although the variable will behave according to the type and the object is created so that it returns a reference and not a direct value. Actually equal to the pointer.

The reference has limitations of what it can do with respect to the pointer, which even allows certain optimizations by the compiler. For example it does not allow a NULL value, nor can it point to something arbitrary, so it is a much safer mechanism.

It cannot be confused with an *array* either, unlike the pointer. It can even point to a memory location that is a array, but it's not the same thing.

If these symbols did not exist, a pointer would probably be declared like this:

const pointer<MyClass> my_class = object.getMyClass();

And therefore a reference Series:

const reference<MyClass> my_class = object.getMyClass();

Since the type is the combination of the two names (one reads reference to an object MyClass) Some people prefer the syntax like this:

const MyClass& my_class = object.getMyClass();

Others prefer this:

const MyClass &my_class = object.getMyClass();

Is strange because the symbol is not part of the variable, but C had and C++ also has a problem in the form of declaration, and the symbol is not acquired by all variables on the same line, so it can make confusion when approaching the name of the main type. Nothing to ever declare two variables in the same line do not solve.

You can see more about the conceptual differences in What is the difference between pointer and reference?.

Documentation .

 1
Author: Maniero, 2020-12-23 14:59:33