Passing by reference

I am fairly comfortable with passing by reference, and I know generally why programmers do this. Is there any stylistic reason why the author of "Beginning game programming through C++" passes a reference to name to the class "Critter" in the following example? I am attaching a fairly long program sample, and I hope it is not a hassle to look at. I tried running the program with and without the "&" and there is no difference.

//Critter Farm
//Deomnstrates object containment

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Critter
Critter(const string name);
string GetName() const;

string m_name;

Critter::Critter(const string name):

inline string Critter::GetName() const
return m_name;

class Farm
Farm(int spaces = 1);
void Add(const Critter& aCritter);
void RollCall() const;

vector<Critter> m_Critters;

Farm::Farm(int spaces)

void Farm::Add(const Critter& aCritter)

void Farm::RollCall() const
for(vector<Critter>::const_iterator iter = m_Critters.begin();
iter != m_Critters.end();
cout << iter -> GetName() << " here.\n";
int main()
Critter crit("Poochie");
cout << "My critter's name is " << crit.GetName() << endl;

cout << "\nCreating critter farm. \n";
Farm myFarm(3);

cout << "\nAdding three critters to the farm.\n";

cout << "\nCalling Roll...\n";

return 0;
Oh and thanks for the help - Julian
(I'm assuming you're talking about the constructor of Critter and forgot to undo the changes you made)

Usually potentially large or complex types are passed by reference even though the function doesn't plan on changing them (notice the const).

This is for performance reasons. If you don't pass something like a string object by reference, a new variable will be created and the object will be passed by value, resulting in a copy that can be expensive in some situations.

This isn't done with primitive types (int, long, bool) because copying primitive types isn't that expensive. In some cases, passing a primitive type by reference can be slower than passing by value.

PS: Use the code tag button (looks like <>) to the right --> when posting code.
Last edited on
Thank you
-your partner in high fiber dieting
Topic archived. No new replies allowed.