References

Q: How did we swap between two ints in C ? A: Pointers

#include <iostream>
using namespace std;

void swap (int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
};

int main() {
    int a=1, b=2;
    swap(a,b);
    cout << "a: "<<a<<", b:"<<b;
}

In C++ instead of using pointers we use references. To use a reference use the & sign before the varible name. If we replace pointer with references we will get:

void swap (int &a, int &b) {
    int t = a;
    a = b;
    b = t;
};

int main() {
    int a=1, b=2;
    swap(a,b);
    cout << "a: "<<a<<", b:"<<b;
}

References vs Pointers

Even though similar there are differences. A pointer can be declared as void but a reference can never be void

3 differences:

  • Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.

  • References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.

  • A reference must be initialized when declared. There is no such restriction with pointers

References are safer and easier to use:

  • Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist.

  • Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration

Creditsarrow-up-right

Lvalue & Rvalue

Lvalue = Left Value – can appear at left side of =. = Located Value – has a fixed memory location. Examples: variables, references …

Rvalue = not Left Value. Numbers, temporaries

Passing arguments by const reference

Passing by regular reference. The function may change the value but the object isn't copied.

Passing by const reference. The function can't change the value and the object isn't copied.

Return a reference to variable

Notice the following:

this is possible because int& get(size_t i) returns a reference. Also the following possible for the same reason.

This is how in an oridnary array we are able to both get and set a value

TODO page 14 in presentation

Call chaining

Notice the syntax of the following line:

Since the function add returns Point& we were able to call a function on the result.

If we were to change the add function to this

We are able to chain the result each time to achieve the same result.

If we wanted to we could endlessly chain add

Last updated