Home

Reference Variables in C++

|
Updated:  
2016-03-26 08:29:45
|
From The Book:  
C++ Essentials For Dummies
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

10

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 is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Jeff Cogswell has been an application developer and trainer for 18 years, working with clients from startups to Fortune 500 companies. He has developed courses on C++ and other technologies.