Skip to content

C++ Crash Course - Ch 3 - POINTERS and REFERENCES

Pointers

int x { 42 };
int* my_ptr = &x;   // & is the 'address_of' operator
printf("my_ptr: %p\n", my_ptr);
printf("*my_ptr: %\n", *my_ptr);   // * is the 'derefence' operator


struct Book {
    char name[256];
    int year;
}

Book book;
Book* book_ptr= &book;

book_ptr->year;  // the -> is the member of operator, it replaces this...
(*book_ptr).year;

Array Decay

Arrays decay into pointers very easily.

int my_nums[] { 1, 2, 3, 4, 5 };

print_nums(my_nums);

void print_nums(int *nums) {    // the array has decayed into a pointer here
    ...
}

void * and std::byte*

void * pointers - cannot be deferenced. Pointer arithmetic not allowed/valid

std::byte * pointers allow for bitwise operations

nullptr

Pointers have an implicit conversion to booleans. Any pointer other than a nullptr is considered true. nullptr is false.

References

int my_int = 42;
int& my_int_ref = my_int;
  • cannot be (easily) assigned to null.
  • once set, cannot be set to refer to a different object (cannot be reseated)

Because references cannot be reseated, they cannot be used for structures such as linked lists.

Const

Const arguments

void do_stuff(const int x) {
// this method cannot change the value of x, if it should attempt to, a compile time error will occur
}

const arguments also work with references and pointers, not allowing their contents to be changed.

Const functions

Used for class methods only. Guarantees that the method will not change the contents of its object

int getValue() const {
  // this method cannot change any part of the object it belongs to
}

Const member variables

struct Coord {
  const float x;
  const float y;

  Coord(float i, float j) : x { i }, y { j }  {}
}

const member variables can only be initialised either when they are declared or when they appear in a constructor's Member Initialiser List. (e.g. x { i }, y { j } in the above example).

The Member Initialiser List is executed before the constructor. Items should be placed in the list in the same order as they appear in the class as their constructors will be called in this order.

Auto

The C++ compiler can infer the type from some initialisers. In these cases the auto keyword can be used.

auto answer = 42;

The auto keyword can also be combined with *, & and const