Suppose there is a class Item . Create a class object and a pointer to the object:

 Item object = new Item(); Item *ptObj = new Item(); 

We can now access members using . and -> for object and *ptObj respectively.

Actually, the question is: How are object and *ptObj in memory?

  • Here is this Item object = new Item(); are you compiling exactly? (unless of course the Item() {}; and Item(Item*) {}; ) constructors are explicitly specified - Vladimir Gamalyan
  • The object itself is a structure consisting of all non-static class fields. A pointer to it represents its memory address, the size of the address depends on the architecture: 32 bits for x86-32 and 64 bits for x86-64, respectively. - cridnirk pm

2 answers 2

This

 Item object = new Item(); 

you will not compile, unless you have declared an Item::Item(Item *item) constructor. But now is not about that. I think you meant

 Item object; 

This entry creates an object of the class Item on the stack.

And here

 Item *ptObj = new Item(); 

you declare a pointer-type variable on the stack and put into it the address of the object created on the heap.

The main difference is where the Item is located. In the first case, it is on the stack. In the second case, on the heap at some address, which is stored in the variable ptObj , which, in turn, is located on the stack.

  • Item object; it is not necessarily in the stack. - Vladimir Gamalyan
  • @Vladimir Gamalian, do you mean the case when this field is an object in the heap? - yrHeTaTeJlb
  • still when it is a global variable, or as static declared .. - Vladimir Gamalyan

A pointer in the memory is a number, which in this case is also some address. A dynamically created object is likely to be a dedicated area of ​​memory.