CS 70

Key Points

  • Goat speaking

    So what do I actually need to know here?

Pointers in General

  • Pointers are a kind of value that represents the memory address of a value of a particular type.
    • Example: int* x means that x will hold a pointer to an int. A pointer to an int (a.k.a. "int pointer") is the address of a piece of memory that purports to contain an int.
    • We can access the data a pointer points to by following it using the indirection operator: *x is another name for the data that x points to.
      • Note: Sometimes people with a C background say "dereference" instead of "follow" (and call * "the dereference operator"). That term is a bit less clear, especially given that it has nothing to do with C++ references. We're trying hard to stick to the C++ terminology in this class (although we might slip up occasionally!).
    • We can read types involving pointers (and more) using the inside-out rule.
  • Pointers are primitive types in C++.
    • There are infinitely many pointer types, because for every (non-reference) type, we can add a * to the end of the type to create a pointer for that type.
    • Pointers support const for setting read-only status. We can use const on the pointer itself, the value the pointer points to, or both.
    • If we let a pointer be default initialized, it will point to an indeterminate value. (From a "did you follow the rules" perspective, a default-initialized pointer is invalid and inappropriate to follow; doing so leads to undefined behavior.)
  • Pointers are useful!
    • We can pass arrays into functions using pointers, with either
      • A first-element pointer and a size; or
      • A first-element pointer and a past-the-end pointer (which is C++'s preferred way).
    • We can also use pointers to avoid moving or copying data, by rearranging the pointers-to-data rather than rearranging the data itself.
  • Every piece of data has a memory address.
    • We can get the address of a variable using the address-of operator: &.
    • Example: if we have int x, then &x is the address of x.
    • (Not to be confused with & as part of a type: int& r is a reference to an int, not the address of the int.)
    • We almost never need to use the address-of operator.

Pointers and Instances of Classes

  • In a member function, this is a pointer to the object that the member function was invoked on.
    • We almost never need to use this; when we do, it's usually as *this.
  • If we have a pointer to an instance of a class, there are two ways to access the members of the object:
    • Follow the pointer, then access: (*myObj).myMemberFunction();
    • Follow and access together (preferred): myObj->myMemberFunction();
  • Pig speaking

    I bet there's even MORE to pointers!

  • LHS Cow speaking

    There is! And that's the next lesson.

(When logged in, completion status appears here.)