1

I've always passed by reference by dereferencing in the function prototype and then referencing the variable when passing in the parameter. I've recently seen what seems to be a way to pass by reference as well but it works slightly different. It references the parameter in the prototype but does not expect any sort of (de)reference when inputting the value into the function. When using my method, you must use the "->" operator to access member functions, but when using the other method you can use the "." operator. Can you please explain the difference between these two methods and if there is a more commonly used method in practice. I have some example code below to better explain what I mean:

#include <iostream>
#include <string>
using namespace std;

void something(string *byRef, string &dontKnow);

int main(int argc, const char * argv[])
{
    string test1 = "test string 1";
    string test2 = "second test";

    something(&test1, test2);

    return 0;
}

void something(string *byRef, string &dontKnow) {
    cout << "test1 address = " << byRef << "\nsize = " << byRef->size() << endl;//size function accessed by "->"
    cout << "test2 address = " << &dontKnow << "\nsize = " << dontKnow.size() << endl;//now accessed by "." and reference operator required for address
}
zeus_masta_funk
  • 1,388
  • 2
  • 11
  • 34

2 Answers2

6

The string &dontKnow is the "official" way of passing by reference, the first way, string *byRef, is passing by pointer by taking the address of the object you want to pass.

It's a bit confusing because the & character is used in two different contexts. See the following line:

something(&test1, test2);

In that line, the ampersand is being used to tell the compiler "pass the address of this variable to the function something", the second parameter without the ampersand is a proper pass by reference.

The first method is not properly passing by reference for a couple of reasons:

  1. If your method accepts a pointer parameter, it could technically receive a NULL pointer, with proper pass by reference, you cannot do this
  2. You're passing a copy of the pointer to the function.
Karl Nicoll
  • 16,090
  • 3
  • 51
  • 65
3

Passing with * is not passing by reference, it's passing by pointer. In a deeper sense it is technically the same thing, but the synthax you have to use when using the object through it's pointer is different. Afaik the only reason to use pointers in C++ is if you want the variable to have the ability to be NULL, or if you want the code to be portable to C.

Havenard
  • 27,022
  • 5
  • 36
  • 62