JavaScript Error

You currently have JavaScript disabled on your web browser.

This website uses JavaScript, and This web page needs JavaScript activated to work correctly.

Please active JavaScript on your web browser and then refresh this web page.



C++ References



A reference is essentially an alias for another variable. It allows you to refer and modify the original variable without making a copy. Any changes made through the reference directly affect the original.

In C++ you are allowed to create a reference to any data type, including built-in types, structs, classes, arrays, and even functions. You can even create multiple references to the same variable, if you so desire, however, keep in mind that references (unlike pointers) cannot be reassigned, meaning each reference stays bound to its initial target for its lifetime.


Key Traits of References


References vs Pointers

Feature Reference Pointer
Must be initialized?YesNo
Can be reassigned?NoYes
Can be null?NoYes
SyntaxMore readableMore flexible

References are declared using the ampersand (&) operator:

 
int myValue = 42;
int& myRef = myValue; // 'myRef' is now another name for 'myValue'

Now, if you modify the value of myRef, you're actually modifying the value of myValue:

 
myRef = 100;
std::cout << myValue; // Outputs 100

Use Cases

Pass-by-Reference in functions:

 
void increment(int& x) {
	x++;
}
int num = 100;
increment(num); // num is now 11

Avoid copies when working with large objects:

 
void printVector(const std::vector<int>& vec);

Reference as return value (use cautiously):

 
int& getElement(std::vector<int>& v, int index) {
	return v[index];
}

Reference to Arrays

When working with arrays, it is often best to pass the array to functions by reference to avoid creating and passing a complete copy of the array:

 
// create an integer array that has 5 elements
int myArr[5] = {12, -59, 74, 7, 106};

// make function to print the array
void printArray(int (&myArr)[5]) {
	for (int i = 0; i < 5; ++i)
	{
		std::cout << myArr[i] << ", "
	}
}

// call the function and pass it the array as an argument
printArray(myArr);	// outputs: 5, 12, -59, 74, 7, 106

The above example requires you to know the exact length (i.e. number of elements) within the array ahead of time, which makes for a good example however in reality it is impractical. A much more flexible method could use a template instead, so that it can accept arrays of any length:

 
// create an integer array that has 5 elements
int a[5] = {12, -59, 74, 7, 106};
int b[77] = {4, 13};

// make function to print the array
template <size_t N&gr;
void printArray(const int (&theArr)[N]) {
	for (size_t i = 0; i < N; ++i)
	{
		std::cout << theArr[i] << ", "
	}
}

// call the function and pass it the arrays as an argument
printArray(a);	// outputs: 5, 12, -59, 74, 7, 106
printArray(b);	// outputs: 77, 4, 13

The above example functions work for all int type arrays, regardless of the length (i.e. number of elements). N is deduced from the array's actual length. You are still passing by reference, which avoids making unnecessary copies of the array.


Memory Address

The & operator can also be used to get the memory address of a variable, which is the exact location of where the variable is stored on the computer.

When a variable is created in C++, a memory address is assigned to that variable. And, when you assign a value to that variable, that value is stored on the computer at that memory address location.

To obtain the memory address of a variable, simply precede the variables name with the & operator:

 
string petsName = "Hairy";
	
std::cout << "Address of petsName is " << &petsName; // Outputs: "Address of petsName is 0x7ffee1b1aabc"

To access the value that is stored at that memory address, you must dereference a pointer to that memory address location:

 
int x = 7;
int* myPointer = &x;   // creates a pointer to the memory address of the variable x
	
std::cout << *myPointer;  // Dereferences the address and gives you x's value of 7

Click Here to learn more about pointers.



Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.


(0) pollYesResult
(0) pollNoResult



 
     About   |   Contact Us   |   Privacy   |   Terms & Conditions   |   © 2025 - T&J Divisions, LLC, All Rights Reserved