Call by Ref VS Dereference operator ?

Why do we need Call by reference?
Compare Code1 with Code2.

Code1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void MakeNice(string& nameRef)
{
	nameRef = "*** " + nameRef + " ***";
}

int _tmain(int argc, _TCHAR* argv[])
{	
	string sName("Kevin");

	MakeNice(sName);

	cout << "Name: " << sName << endl;

	cin.get();
	return 0;
}



Code2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void MakeNice(string* namePtr)
{
	(*(namePtr)) = "*** " + (*(namePtr)) + " ***";
}

int _tmain(int argc, _TCHAR* argv[])
{	
	string sName("Kevin");

	MakeNice(&sName);

	cout << "Name: " << sName << endl;

	cin.get();
	return 0;
}



So, how can call by ref be used where pointers/deref. operator fail?
Or does Call By Ref internally actually do the same thing as in Code2?

Thx,
Xcrypt
they are doing the same thing if Code2 isn't passed a NULL pointer

in fact, if your objective is to return a result, you should prefer using a reference (so there is no need to check for NULL)
Last edited on
Hi there, in your example it doesn't make much difference. But there is a benefit to references for example:
1
2
3
4
5
6
7
8
std::string Concatenate(const std::string& lhs, const std::string& rhs)
{
   return (lhs + rhs);
}
int main (int argc, char * const argv[]) {
   std::cout << Concatenate("Hello, ", "World!") << std::endl;
   return 0;
}

You could not do that by accepting a pointer as an argument. For more information regarding References vs Pointers:
http://en.wikipedia.org/wiki/Reference_(C%2B%2B)#Relationship_to_pointers

I hope this helps.

Phil.
Topic archived. No new replies allowed.