14

I want to declare a string, initialize it by passing it by reference, and then pass it by value to the 'outputfile' function.

The code below works, but I don't know why. In main I would expect to pass the string 'filename' like

startup(&filename)

But that gives an error, and the code below doesn't. Why? Also, is there a better way to do this without using a return value?

#include <iostream>
#include <string>
using namespace std;
void startup(std::string&);
void outputfile(std::string);
int main()
{
    std::string filename;
    startup(filename);
    outputfile(filename);
}   
void startup(std::string& name)
{
    cin >> name;
}
void outputfile(std::string name)
{
    cout << name;
}
Peter
  • 367
  • 1
  • 4
  • 12
  • 2
    `&filename` creates a pointer. Pointers and references are incompatible. –  Feb 08 '15 at 05:28
  • Why do you not want to use a return value? – Chris Drew Feb 08 '15 at 05:35
  • The code "works" because it does *exactly* what you described. in your opening sentence, and does so well. Regarding the error with `&filename`, it shouldn't compile because a reference is not a pointer. See [this question and answers](http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in). regarding their differences and similarities. – WhozCraig Feb 08 '15 at 05:42

1 Answers1

19

Your code works as expected.

&filename returns the memory address of (aka a pointer to) filename, but startup(std::string& name) wants a reference, not a pointer.

References in C++ are simply passed with the normal "pass-by-value" syntax:

startup(filename) takes filename by reference.


If you modified the startup function to take a pointer to an std::string instead:

void startup(std::string* name)

then you would pass it using the address-of operator:

startup(&filename)


As a side note, you should also make the outputfile function take its parameter by reference, because there's no need to copy the string. And since you're not modifying the parameter, you should take it as a const reference:

void outputfile(const std::string& name)

For more info, here are the rules of thumb for C++ regarding how to pass function parameters.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157