Passing by reference

Hello,
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
{
public:
Critter(const string name);
string GetName() const;

private:
string m_name;
};

Critter::Critter(const string name):
m_name(name)
{}

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

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

private:
vector<Critter> m_Critters;
};

Farm::Farm(int spaces)
{
m_Critters.reserve(spaces);
}

void Farm::Add(const Critter& aCritter)
{
m_Critters.push_back(aCritter);
}

void Farm::RollCall() const
{
for(vector<Critter>::const_iterator iter = m_Critters.begin();
iter != m_Critters.end();
++iter)
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";
myFarm.Add(Critter("Moe"));
myFarm.Add(Critter("Larry"));
myFarm.Add(Critter("Curly"));

cout << "\nCalling Roll...\n";
myFarm.RollCall();

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.