Pointers, Exceptions, and Function Calling in C++
Pointers
To start a discussion about pointers, we must recognize the way that a computer stores the values of variables in memory. When the value of a variable is assigned, or rather, whenever any object in C++ is created it is allocated an address in memory where the value of that object is stored in bits. The address itself is usually given as a hexidecimal representation of the location of that object in memory. C++ uses dynamic memory allocation which means that we can create new blocks of memory to store our variables.
A pointer is a variable that stores the address of another variable. To create a pointer, use the * operator and assign a type. The type of object determines the space that is allocated in memory. This operator is also known as the dereference operator and can be used to dereference the address in ptr, to return the value of that variable store there. We use the & operator known as the "address of" operator to return the address of a given variable (to store in a pointer).
int *ptr; #creates a new pointer of type int ptr = &myVar #assigns the address of the data in myVar to ptr *ptr == myVar #dereference the pointer. myVar will be equal to the value in the memory address stored in ptr
Pointers are used in linked lists and other data types. We can also use pointers to pass values into a function by writing a pointer as an argument in the function definition. Then you pass values of the address when using the function.
Function Calling: Pass by Copy and Pass by Reference
When we pass a variable into a function, we are making a copy of that variable to be used in the function. Changes to this function will not be reflected in outside of the function. We can also pass by reference which means that we can modify the variable which is passed to the function. We can also pass by constant reference which means the data supplied as input to the function does not need to be copied in memory, saving time and memory.
Exceptions
When we want to test a certain block of code we can surround it in a try{} block. We write an exception which will determine the type of error and provide a message. After the try{} block we include a catch{} block which will end the program and provide the error message and type from the exception if one is detected. This is useful when we expect a certain function to behave a certain way on certain inputs, like "out of bounds" or "type error". This does not need to be caught at compile time, because some values may be passed in by the user at runtime.