Functions: Pass by reference vs by value

We talked about passing by reference and by value a little bit last time, but there's still plenty of important stuff to cover. We'll start with a brief refresher on the basics. There are two possible reasons to pass by reference. 1) If you want to use a function to edit a variable (instead of editing a copy). 2) For large objects where making a copy wastes too much time and memory. This first .cpp file covers reason (1).


This second .cpp file covers reason (2)


A longer problem

We're going to write a (short) library of functions. I have 3 goals for this segment of the lecture. 1) Learn how to create our own .h and .cpp files (similar to the ones we've been using from Mike), 2) Talk about testing our code as we write it, and 3) general practice with writing functions.

Problem statement: Oh no! For some unexplained reason we forgot how to use some of the standard string functions (specifically, substr, find, and erase). So now we have to write our own from scratch. We'll build myStringLib.h and myStringLib.cpp, then #include those into a main.cpp and use them there. Our makeshift string library will include 3 functions

  1. substr: input a string, a position number, and a number of characters to get. Return a string consisting of the requested characters.
      Ex: substr("Tuesday",2,3) should return "esd"
  2. find: input two strings. The first one will be the (larger) string that we are searching through, and the second will be the (smaller) string that we are searching forr. Return the position number of the first location where we find it. If we never find it, then return string::npos. (this is the same thing as returning -1 if you do it right)
      Ex: find("Hello World!","ll") should return 2.
  3. erase: input a string, a position number, and a number of characters to erase. Edit the string to remove the requested characters. Don't return anything.
      Ex: If str stores "Hello World!", then after running erase(str,3,4) it should store "Helorld!"