0

Here is my problem i try to use class pointers but when i try to get the memory adress of the A class I get a different output

Output:

0148D460 00FAFA84 

Code:

#include "stdafx.h" #include <iostream> #include "TestClass.h" using namespace std; int main() { A *Aobj = new A; B Bobj; cout << Aobj << endl; cout << &Aobj << endl; getchar(); delete Aobj; return 0; } 

3 Answers 3

4

Aobj is pointing to an object on the heap.

 | Stack | | Heap | &Aobj |A* Aobj| --> | new A | |B Bobj | 

The difference between these two outputs is the first one prints the address of the object Aobj is pointing to, on the heap

cout << Aobj << endl; 

and the second one is printing the address of the pointer Aobj on the stack

cout << &Aobj << endl; 
Sign up to request clarification or add additional context in comments.

Comments

0

Pointers are also data

All variables declared locally represents an object that is stored on the stack. The difference between dynamic allocation and automatic objects is that automatic objects store their data directly on the stack, while dynamically allocated objects store a pointer on the stack that points to data on the heap.

When you output a pointer to standard output using the << operator, then what happens is that the objects contents, which is an address to A, is printed out.

When you apply the built-in address-of operator * to an object, then it creates and returns a pointer on the stack that points to the given object. When outputting the returned pointer, in your second case, using <<, then its contents are printed, which is the address to the first pointer.


Think of your memory as a bookshelf. Then a pointer is one of those fake hollow books that you can put something else inside, like a little note with an address to another book (or another fake hollow book). The fake hollow book also has an address, just like the rest of the books, as e.g. third from left, second shelf etc. In this model using the address-of operator on a book creates a new fake hollow book containg a note with an address to the specified book. The heap can be seen as another bookshelf on the other side of the room whose books can be addressed inside fake books in the first bookshelf.

Comments

0
 cout << Aobj << endl; 

is printing the value stored in your variable of type "A*". Meanwhile,

cout << &Aobj << endl; 

is printing the address where that variable is placed in memory.

2 Comments

this is not the correct answer. Look at @olaf-dietsche answer.
I would say that Olaf's answer is more complete and better explained (that's why I voted it up). But I'm not sure why you think this answer is incorrect.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.