General Question About the & Operator

I have a general question about using the reference operator, &. I know that this gives us the address of whatever that follows it (e.g., &x gives us the address of variable x). However, I have seen some confusing notation using this operator, and I wonder if what I'm seeing is something totally different. In particular, suppose I have a class called "something." In this class's header file (and similarly in its cpp file, but using the scope resolution operator), we have the following statement of a public function, f:

void f(const something& object)

where object is an object of type "something." In this situation, does the & symbol indicate that we are taking the address of object? If so, what variable name are we assigning the address to? (That is, is it being assigned to const?) Also, why not write it as follows (which is the notation I would expect)?:

void f(const something &object)

Thanks!
When you call a function:
void f(something *object)
with
f(&MyObject);

This is a C-style (but still very valid) method. Here you are passing the ADDRESS (&) of MyObject into a pointer called object. You can then refer to the original object by using the dereferencer (*) which means "The value at this address". You can write to this object in the function. This will change the original value from the calling function.


When you call a function:
void f(something &object)
with
f(MyObject);

This is a C++-style method called passing by reference. This is effectively the same as the above case, but you don't have to constantly refer to the value at this address with the * in the function. You can write to this object in the function. This will change the original value from the calling function.

When you call a function:
void f(const something &object)
with
f(MyObject);

This is sort of like the case above except that the object comes in as read-only. This means you'll get a compilation error if you try to write to it. You may ask why we would do something like this instead of just omitting the const and & symbols. If you just input the object without the reference (&) and const, then it creates a new object and copies all of the data from the original. This object is destroyed at the end of the function. If you have a class which is HUGE, then this can be quite slow so doing it this with the const and & will be better.
Last edited on
So, when I see

 
void f(const something& object)


I should read this as

 
void f(const something &object)


? If so, why do some people write & at the end of "something," instead of in the front of "object"?
To add even more confusion this is legal as well and is the same thing as the above 2.
void f(something const&object)
It's just how some people like to do things. The spaces don't really matter. If you work for a company, you'll often have coding standards to standardize this.
Thanks! That helps clarify things.
Topic archived. No new replies allowed.