theres something I dont understand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  // classes and default constructors
#include <iostream>
#include <string>
using namespace std;

class Example3 {
    string data;
  public:
    Example3 (const string& str) : data(str) {}
    Example3() {}
    const string& content() const {return data;}
};

int main () {
  Example3 foo;
  Example3 bar ("Example");

  cout << "bar's content: " << bar.content() << '\n';
  return 0;
}


thats an example from the tutorial..
why does the string in Example3 (const string& str) : data(str) {}
contains &
The '&' is the address-of operator, but what they're doing is sending the string by a const reference. The const prevents modification, and sending it by reference avoids creating a copy of the string.
Sending a parameter by value (without the reference) will send a copy of the argument (assuming a copy constructor is available). Sending a parameter by reference will send the original object itself as the parameter instead of a copy. Using const ensures it will not be modified.
See also, "Efficiency considerations and const references" in the tutorial:
http://www.cplusplus.com/doc/tutorial/functions/
Topic archived. No new replies allowed.