5. Pointers and References

About this Tutorial –

Objectives –

This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.

Audience

Students who are new to object orientation (or programming) and need to learn C++.

Prerequisites

No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The C++ course covers these topics and more:

  • Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
  • Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
  • Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures

Download Solutions

Java tutorial


Overview

Estimated Time – 0.5 Hours

Not what you are looking? Try the next tutorial – Going Further with Types

  1. A pointer is a variable that holds an address
    • When you declare the pointer, you must specify what data type the pointer points to
  2. C++ provides special syntax to do the following:
    • Declare a pointer, indicating what type it points to
    • Set a pointer, to hold the address of a variable
    • Dereference a pointer, to get the contents of the variable at the address indicated by the pointer

Lab 1: Pointers

Lab 1: Pointers
  1. Declaring Pointers
    • To declare a pointer:
      • Use * in the declaration
      • You don’t have to initialize the pointer in the declaration
        type * pointerVariable;
    • Examples:
      int * int_ptr;
      double * double_ptr;
      Person * person_ptr;
    • You can declare several pointers in the same statement
      • You must use a separate * for each pointer variable
        int * int_ptr1, * int_ptr2, * int_ptr3;
  2. Pointer1

  3. Setting Pointers
    • Pointer variables hold addresses
      • Use & to get the address of a variable
        pointerVariable = &variable;
    • To set a pointer:
      • Either initialize it with an address in the declaration…
      • And/or assign it an address later on
    • Examples:
      int num1, num2; // num1 and num2 are integers.
      int * ptr1 = &num1; // ptr1 holds the address of num1.
      int * ptr2; // ptr2 is uninitialized, so it could point anywhere!
      ptr2 = &num2; // ptr2 now holds the address of num2.
      ptr1 = ptr2; // What does this do?
  4. Dereferencing Pointers
    • To dereference a pointer, use the * operator
      • Gets the contents at the address indicated by the pointer
        *pointerVariable
    • Examples:
      int num1 = 56; // num1 is an integer.
      int * ptr1 = &num1; // ptr1 holds the address of num1.
      cout << *ptr1; // Effectively outputs num1. *ptr1 = 42; // Effectively sets num1 to 42.
    • What do these statements do?
      ++*ptr1;
      *ptr1++;
      (*ptr1)++;
  5. Using Pointers with Arrays
    • You can use pointers to traverse an array
      • An alternative to using [n] indexing
    • Example:
      • Set a pointer to the first element in an array
      • Loop until you reach the end of the array
      • On each iteration, access the current element, and then increment the pointer to the next element
        int lotteryNumbers[6] = { ... };
        int * pCur = &lotteryNumbers[0]; // Can just say "lotteryNumbers" here.
        int * pEnd = pCur + 6; // Pointer arithmetic is scaled by element size.
        while (pCur < pEnd) {  cout << *pCur++; }
  6. Null Pointers
    • Sometimes you're not sure what to initialize a pointer with
      • But... uninitialized pointers are very dangerous!!!
    • Sometimes you want to "unset" a pointer
      • To indicate that the pointer no longer points to a real value
    • C++ supports the concept of null pointers for these cases
      • A null pointer is a pointer with the address 0
      • You can set a pointer to 0, and test against it safely
        int * ptr1 = 0; // Set it to a null pointer initially.
        ...
        if (ptr1 != 0) // See if the pointer now holds a real address.
        {
         // Use ptr1 here.
        }
  7. Using const in Pointer Declarations
    • You can use const in pointer declarations
    • You can declare a "pointer to constant data"
      • Prevents you from modifying data via a pointer
      • Protects data from accidental modification via the pointer
        const int * ptr1;
    • You can declare a "constant pointer"
      • You MUST assign an address in the declaration
      • The pointer will always point to the same address
      • Useful in low-level programming (where you want to access a particular address)
        int * const ptr1 = &someVariable;
Lab
  1. Traversing an array using pointers
  2. In Visual Studio, create a new C++ project named PointersReferencesApp in the student folder. Write a function as follows:
    • Takes an array of doubles, and returns the average value. Use pointers to traverse the array (to practice using pointer arithmetic)
      double CalculateAverage(const double *pData, int count)
      {
       const double *pEnd = pData + count;
       double total = 0;
       while (pData != pEnd)
       {
        total += *pData++;
       }
       return total / count;
      }
    • View code file.
    • Remember to make good use of const
  3. Call the function from main()
    double average = CalculateAverage(array, 5);
    cout << "Average value: " << average << endl << endl;
  4. View code file.

Lab 2: Reference variables

Lab 2: Reference variables
  1. A reference is an alias for another variable
    • Similar-ish to a const pointer
  2. Pointer2

  3. But... references are automatically dereferenced on usage
    • No need to use * to get at the data
  4. Declaring Reference Variables
    • To declare a reference variable:
      • Use & in the declaration
      • You MUST initialize the reference variable in the declaration
      • The reference variable will always refer to the same variable
        type & referenceVariable = aVariable;
    • Examples:
      int someInt;
      double someDouble;
      Person somePerson;
      int & refInt = someInt;
      double & refDouble = someDouble;
      Person & refPerson = somePerson;
  5. Using Reference Variables
    • A reference variable is an alias to another variable
      • Automatically dereferenced on usage
      • You don't use the * (contents-of) operator to get at the value
    • Examples:
      int someInt;
      int & refInt = someInt;
      // The following 2 statements have identical effect:
      someInt = 42;
      refInt = 42;
  6. Null Reference Variables: no such thing
    • There is no such thing as a null reference variable!
      • A reference variable always points to a legitimate variable
      • There is no way to say "this reference variable doesn't refer to a variable at the moment"
  7. Using const in Reference Declarations
    • You can use const in reference declarations
    • You can declare a "reference to constant data"
      • Prevents you from modifying data via a reference
      • Protects data from accidental modification via the reference
        const int & ref = someInt;
    • You don't need to declare a "constant reference"
      • References are always const, by definition
      • i.e. they always point to the same place
Lab
  1. Finding the largest item in a range
    • Write a function as follows:
      • Takes an array of doubles, and returns a pointer to the largest item
        const double * FindMax(const double *pData, int count)
        {
         const double *pLargest = pData;
         const double *pEnd = pData + count;
         // Loop through all elements, to see which is the largest.
         for (const double *pEnd = pData + count; pData != pEnd; pData++)
         {
          if (*pData > *pLargest)
          {
           pLargest = pData;
          }
         }
         return pLargest;
        }
      • View code file.
      • Note - don't return a "copy" of the largest item!
    • Call the function from main()
      const double *pLargest = FindMax(array, 5);
      cout << "Largest item: " << *pLargest << endl;
    • View code file.

Lab 3: Function parameters revisited

Lab 3: Function parameters revisited
  1. Pass-By-Value
    • By default in C++, all parameters are passed-by-value
      • Except arrays, of course!
    • Here's a quick reminder:
      // Client
      int n = 10;
      cout << "Here are 5 numbers, starting at " << n << endl; displayNumberRange(n, 5); cout << "Did you notice the first number was " << n << endl; // Function void displayNumberRange(int num, int count) {  int lastNum = num + count;  while (num < lastNum)   cout << num++ << endl; }
  2. Pass-By-Pointer
    • You can pass parameters by pointer
      • Declare the function to take pointer variables
      • Pass addresses into the function
      • Function can modify underlying data (unless pointer is const)
    • Example:
      //Client
      double height, weight;
      getPersonInfo1(&height, &weight);
      cout << "Height: " << height << ", weight: " << weight << endl; // Function void getPersonInfo1(double * ph, double * pw) {  cout << "Enter your height: ";  cin >> *ph;
       cout << "Now enter your weight: ";  cin >> *pw;
      }
  3. Pass-By-Reference
    • You can pass parameters by reference
      • Declare the function to take reference variables
      • Pass variables (not addresses) into the function
      • Function can modify underlying data (unless reference is const)
    • Example:
      // Client
      double height, weight;
      getPersonInfo2(height, weight);
      cout << "Height: " << height << ", weight: " << weight << endl // Function void getPersonInfo2(double & h, double & w) {  cout << "Enter your height: ";  cin >> h;
       cout << "Now enter your weight: ";  cin >> w;
      }
  4. Using Const References
    • It's extremely common to pass objects as const reference into functions
      • Pass-by-reference for efficiency (to avoid expensive object copy
      • Declare as const to protect against unwanted modification
    • A good example is passing strings into functions
      • Pass-by-value works (but is inefficient)
      • Pass-by-const-reference works better (no need for copying)
        // Client
        string firstName = "Michael";
        string surName = "Laudrup";
        string fullName = getFullName(firstName, surName);
        cout << "Full name: " << fullName; // Function string getFullName(const string & fn,        const string & sn) {  return fn + " " + sn; }
Lab
  1. Using pointers to pointers
    • Write a function as follows:
      • Takes an array of doubles, and yields pointers to the min and max elements
        void FindMinAndMax(const double * pData, int count, const double **ppMin, const double ** ppMax)
        {
         // Set first element as min and max element, as a starting point.
         *ppMin = pData;
         *ppMax = pData;
         
         // Loop through all elements, to see which is the smallest and largest.
         for (const double *pEnd = pData + count; pData != pEnd; pData++)
         {
          if (*pData < **ppMin)   {    *ppMin = pData;   }   if (*pData > **ppMax)
          {
           *ppMax = pData;
          }
         }
        }
      • View code file.
      • Note - use pointers to pointers!
    • Call the function from main()
      const double *pMin, *pMax;
      FindMinAndMax(array, 5, &pMin, &pMax);
      cout << "Min item: " << *pMin << ", Max item: " << *pMax << endl;
    • View code file.

 

Well done. You have completed the tutorial in the C++ course. The next tutorial is

6. Going Further with Types


Back to beginning
Copyright © 2016 TalkIT®





If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top