Hi Guys...

I have some basic doubts with references and pointers and need some understanding on the behavior of this code

#include <iostream>

using namespace std;

class a
{
	public:
		int getAmount(a&);
	private:
		int amount;
};

int
a::getAmount(a& p)
{
	cout << this << endl;
	cout << p << endl;
	//cout << &p << endl;
	return amount;
}

int main()
{
	a *obj = new a();
	obj->getAmount(*obj);
	//a obj1;
	//obj1.getAmount(obj1);
};

When i'm passing *obj to getAmount, i realize i'm passing the object to it, and the parameter is a&, so my understanding is that 'p' now should be my reference to the object and cout << p, should work. But i get compilation error that operator << is not overloaded for type 'a'(which means that 'p' is the actual object itself). instead cout << &p works and gives me the address. Why is that so?

If from main i use the commented code then both cout << p and cout << &p work the same and give me the address of the object in memory. Thus here 'p' works as a reference to the object.

p is the object itself (just another name for *obj, not obj). References are internally treated as pointers. However, it is hidden from the programmer.

>If from main i use the commented code then both cout << p and
>cout << &p work the same and give me the address of the object
>in memory. Thus here 'p' works as a reference to the object.
C++ uses operators (and keywords) multiple times and for wildly different purposes. For example, * could mean a pointer in a declaration, indirection on a pointer, or arithmetic multiplication:

#include <iostream>

int main()
{
  int *pa = new int ( 10 );
  int *pb = new int ( 2 );

  std::cout<< *pa * *pb <<'\n';

  delete pb;
  delete pa;
}

What you're seeing is the same difference. & in a declaration means that the object is a reference, but & as a prefix operator means to evaluate to the address of the object:

#include <iostream>

int main()
{
  int a = 10;
  int& ra = a;

  std::cout<< a <<'\t'<< &a <<'\n';
  std::cout<< ra <<'\t'<< &ra <<'\n';
}

When you create a reference, you're effectively creating a synonym for the original object. In the above program, ra is a, just with a different name. ra is a synonym for a, so when you say &ra (taking the address of ra), it's identical to saying &a.

Hi Narue,

That was a very nice explanation, Thank you. i realize that i can also create a reference to an object on the heap like this..

int main()
{
	a *obj = new a();
	a& b = *obj;	
};
This article has been dead for over six months. Start a new discussion instead.