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

Asked

Viewed 56 times

1

I noticed that some statements of variables/objects are used * for the statement (thus generating a pointer), but in some cases has the statement using &.

const MyClass & my_class = object.getMyClass();

What is the purpose of "&" when declaring an object?

  • is an operator of bitwise, i.e., bit-level logic operation. I cannot write a response now, but you can read more here: https://tecdicas.com/bitwise-em-cpp/

1 answer

1


This symbol indicates that you are creating a reference instead of a pointer, but it works analogously (not equally).

It is part of the type and not the variable, much less 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 the same as the pointer.

The reference has limitations on what it can do relative 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.

He can’t be confused with an *array* also, unlike the pointer. It may even point to a memory location that is a array, but it’s not the same.

If there were no such symbols probably a pointer would be declared so:

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

and therefore a reference would be:

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

Since the type is the combination of the two names (reference is read for an object MyClass) some people prefer the syntax like this:

const MyClass& my_class = object.getMyClass();

Others prefer it this way:

const MyClass &my_class = object.getMyClass();

It 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 be confusing when approaching the name of the main type. Nothing that never declaring two variables on the same line does not solve.

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

Documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.