5

Suppose I have a C++ class as follows:

class Point {
// implementing some operations
}

Then:

Point p1;
Point p2 = p1;

If I want to know the address of p2, then I can use &p2. But how can I get the address that p2 stores? Because p2 is not a pointer, so I cannot just use cout << p2;

Matt
  • 22,721
  • 17
  • 71
  • 112
ipkiss
  • 13,311
  • 33
  • 88
  • 123

3 Answers3

16

What's wrong with the following:

cout << &p2;

As you say, p2 is not a pointer. Conceptually it is a block of data stored somewhere in memory. &p2 is the address of this block. When you do:

Point p2 = p1;

...that data is copied to the block 'labelled' p1.

But how can I get the address that p2 stores?

Unless you add a pointer member to the Point data structure, it doesn't store an address. As you said, it's not a pointer.

P.S. The hex stream operator might be useful too:

cout << hex << &p2 << endl;
Juan
  • 198
  • 1
  • 14
sje397
  • 41,293
  • 8
  • 87
  • 103
  • 1
    [Beware if the object is actually a `char`](http://stackoverflow.com/questions/5657123/how-to-simulate-printfs-p-format-when-using-stdcout/5657144#5657144). – Xeo May 16 '11 at 00:22
  • 2
    What's wrong with answers that start with, "what's wrong with"? – Roger Dahl Oct 17 '20 at 20:39
4

By doing

Point p2 = p1;

you simply copy the values of p2 onto p1 (most likely). The memory is independent. If you did instead:

Point* p2 = &p1;

then p2 will be a pointer onto p1 (printing its value will give you the begining of the memory block, you could then try the sizeof to get the size of the block).

hauron
  • 4,550
  • 5
  • 35
  • 52
  • 1
    Hi Hauron. "copy the values of p2 onto p1" should be the other way around. Good example with the pointer, but should be `sizeof` (no underscore) and anyway you can get the size of the object with `sizeof(Point)` or `sizeof p1` as well as `sizeof *p2` for your pointer version thereof. Cheers. – Tony Delroy May 16 '11 at 03:17
2

The accepted answer proposes the use of operator & to obtain the address of an object.

As of C++11, this solution does not work if the object class defines/overloads operator &.

In order to get the address of an object, from C++11, the template function std::addressof() should be used instead.

Point p1;
Point* p2 = std::addressof(p1);

http://www.cplusplus.com/reference/memory/addressof/

shrike
  • 4,449
  • 2
  • 22
  • 38