PDA

View Full Version : Question about pointer to class



kaydknight
17th January 2007, 05:47
Hi I have a question on pointer to class, please have a look at the snippet below:

Code to instantiate the class through use of pointer



#include <iostream>
using namespace std;

class Rect
{
public:
int x;
Rect();
};
Rect::Rect()
{
x = 5;
}

int main()
{
Rect *re = new Rect;
std::cout << re << std::endl;
std::cout << &re << std::endl;
std::cout << re->x << std::endl;
system("PAUSE");
return 0;
}
*/

Below is the result from the console:


0x33ffc0
0x23ff70
5

My question, when I try to output re to the console, I assume it will take the address of the object instantiated, and it wrote 0x33ffc0, but when I called for &re, it wrote 0x23ff70. Doesn't &re means I'm displaying the address of the variable pointing to?

So why are they different?
I thought that re contains the address of the object instantiated, and &re should get the address of the object too, as defined in most tutorials on pointer.


doing std::cout << *re will give me an error. I understand from the concept of pointers, that *var will get the value pointed by the pointer. Is my assumption correct that the value is of an object and can't be displayed?

Thanks for reading this, I'm very curious at this, but it's indeed interesting to me!

guestgulkan
17th January 2007, 08:15
No.
re and &re are not the same.
re is a pointer to the variable of class rect. so re is a *Rect

&re is the address of where the pointer re is stored.
So &re is **Rect