-1

I am having a little confusion about memory allocation. Where does member variable get created (on stack or heap?) when object is created on heap? For example, say we have class Cat as follows.

class Cat { public: int itsage;};

Now suppose we have following line of code in main function.

Cat * Frisky= new Cat;

Now I guess here pointer variable Frisky is created on stack which stores memory address of memory on heap(Am I right?). But I am confused where is integer variable itsage is created? Also what will happen if itsage was itself pointer? i.e. int * itsage;

Thanks.

Believer
  • 261
  • 1
  • 8
  • Someone needs to come along and post the good book link. – sweenish Aug 11 '20 at 18:29
  • 2
    This should be covered in any introductory text. Here are some good [books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to choose from. – cigien Aug 11 '20 at 18:32

1 Answers1

3

itsage is a subobject of Cat which means it is part of the the Cat object itself. Therefore, it exists as part of the heap-allocated Cat object. new Cat creates the Cat object and any subobjects, all within the same allocation.

If it were a pointer, this would still be true. The pointer value would be part of the Cat object, but it could point to an int somewhere else.

Note that the C++ standard doesn't use the terms "stack" and "heap." Function local variables (non-static) have automatic storage duration and objects created with new T have dynamic storage duration. Under the hood, values with these storage durations are typically implemented using the stack and heap respectively, but a conforming implementation is not required to use stack or heap structures.

cdhowie
  • 158,093
  • 24
  • 286
  • 300