C++ All-in-One For Dummies, 4th Edition
Book image
Explore Book Buy On Amazon

Declaring a variable that is a reference is easy. Whereas the pointer uses an asterisk, *, the reference uses an ampersand, &. But there’s a twist to it. You cannot just declare it like this:

int &BestReference; // Nope! This won't work!

If you try this, you see an error that says BestReferencedeclaredasreferencebutnotinitialized. That sounds like a hint: Looks like you need to initialize it.

Yes, references need to be initialized. As the name implies, reference refers to another variable. Therefore, you need to initialize the reference so it refers to some other variable, like so:

int ImSomebody;
int &BestReference = ImSomebody;

Now, from this point on, forever until the end of eternity (or at least as long as the function containing these two lines runs), the variable BestReference will refer to — that is, be an alias for — ImSomebody.

And so, if you type

BestReference = 10;

then you’ll really be setting ImSomebody to 10. So take a look at this code that could go inside a main():

int ImSomebody;
int &BestReference = ImSomebody;
BestReference = 10;
cout << ImSomebody << endl;

When you run this code, you see the output


That is, setting BestReference to 10 caused ImSomebody to change to 10, which you can see when you print out the value of ImSomebody.

That’s what a reference does: It refers to another variable.

Because a reference refers to another variable, that implies that you cannot have a reference to just a number, as in int&x=10. And, in fact, the offending line has been implicated: You are not allowed to do that. You can only have a reference that refers to another variable.

About This Article

This article is from the book:

About the book author:

John Paul Mueller has written more than 100 books and more than 600 articles on topics ranging from functional programming techniques to application development using C++.

This article can be found in the category: