C++/References and Pointers

From Wikiversity
< C++
Jump to: navigation, search

Reading Assignments[edit]

Variables and User Input
Functions and Recursion

Introduction[edit]

From the Variable and User Input and Functions and Recursion reading assignments you may have learnt that variables store a value of some type and that each variable is given an address to a block or portion of computer memory capable of storing a value of that type. You may also have learnt that function parameters can pass by value or pass by reference. Function parameters are one area in which references and pointers are beneficial as will be explained later on.

To summarise what references and pointers do, they "refer to" or "point to" a variable respectively, but they are not the variable itself. An illustration to help you understand this concept is that of a postal address. A postal address "refers to" or "points to" a particular property but it is not the property itself.

The following exercises will highlight the advantages and disadvantages of using references and pointers, but most importantly, give you the reader a chance to try it yourself. For more in-depth material on these two aspects of C++ I suggest searching the internet or wikibooks and wikipedia.

Lesson ? References and Pointers[edit]

Let us begin by looking at references.

Declaring and Initializing a Reference[edit]

Example:

#include <iostream> // For standard input/output functions

using namespace std;

int main(int argc, char* const argv[]) {

    int  myAge  = 21;        // Declare and initialize an address
    int& refToMyAge = myAge; // Declare and initialize a reference to myAge

    cout << "myAge is: "      << myAge      << endl; // Display myAge in the console window
    cout << "refToMyAge is: " << refToMyAge << endl; // Display refToMyAge in the console window

    return 0;
}

Simple! No doubt the above example does not need explaining but the comments are there if you require them. As a test, try and assign the value 0 to refToMyAge and see what happens. Lets move on to something a little more interesting.

Using References as Function Parameters[edit]

Lets look at an example of using references as function parameters.

Example:

#include <iostream>

using namespace std;

void printAge(int& age) // Declaration and definition of fctn function
{
    cout << "You are " << age << " years old!" << endl;
    cout << "Increasing your age by 1 year..." << endl;
    age = age+1;
}

int main(int argc, char* const argv[]) {

    int myAge = 0;                     // Declare an initialize myAge to a default value

    cout << "How old are you? ";
    cin >> myAge;                      // Ask user how old they are

    printAge(myAge);                   // Call printAge() to display a message

    cout << "You are now " << myAge << " years old!" << endl; // Confirm that the user is older

    return 0;
}

Admittedly it is a rather pointless program but it demonstrates an ability that references (and pointers) have. Did you notice it? Well if you didn't here is an explanation for you.

myAge is a variable declared outside of the printAge() function definition or body. But, the value of myAge was changed from inside the printAge() function. How did it do that? Well simply because the parameter int& age is a reference, therefore it "refers to" whatever variable is input when that function is called e.g. myAge.

Advantages of References[edit]

So what are some advantages to using references?

  • You can modify variables of different types outside of a function from inside the function without specifying the return keyword or return type in the function prototype or definition.
  • You are not passing the value of variable into the function itself but rather the address of a particular variable meaning better efficiency in terms of memory usage.
  • They are regarded as being safer than pointers in terms of memory management since with pointers, the programmer is responsible for deletion or cleaning up after use unlike references.

Now lets go on to considering pointers.

Declaring and Initializing a Pointer[edit]

Example:

#include <iostream>

using namespace std;

int main(int argc, char* const argv[]) {

    int myAge = 20;           // Declare and initialize myAge variable to 20
    int* ptrToMyAge = &myAge; // Declare and initialize a pointer to myAge

    cout << "myAge is: "      << myAge       << endl; // Display myAge in the console window
    cout << "ptrToMyAge is: " << *ptrToMyAge << endl; // Display refToMyAge in the console window

    return 0;
}

As you can see there are very few differences compared to the references example, but the differences are important. So I shall briefly explain them to you.

Firstly, you use an asterisk (*) to declare a pointer instead of an ampersand (&) as with references. A pointer stores the address of a particular variable, and to get that address you place an ampersand (&) before the variable name like so: int* ptrToMyAge = &myAge;. To get the value of the variable at that address you have to dereference the pointer like so: *ptrToMyAge.

Now, lets try something out. Remember I asked you to assign the value 0 to a reference? Try it with a pointer and see what happens. Next, remove the dereference from ptrToMyAge and see what happens.

Where To Go Next[edit]

Topics in C++
Beginners Data Structures Advanced
Part of the School of Computer Science