Search code examples
c++memory-address

Get the address of class's object in C++?


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;


Solution

  • 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;