简体   繁体   中英

Where does a stack object inside a heap allocated object gets allocated in c++?

Iam having two classes Class A and Class B .

class A
{
  int width;
  int height;  

};

class B
{
  A obj;

};

i'm trying to create a pointer like below

B* myObj = new B();

Here, myObj gets created in the heap. where does obj , width and height gets created?

The pointer to the object, called myObj in your program, is created on the stack.

The object itself B() is created on the heap. width and height are contained within the memory taken up by B() and are thus also on the heap.

In Ascii Art:

Stack --- myObj
            |
Heap      [ B -- A [ Width, Height ] ]

Objects can contain other objects, called subobjects. A subobject can be a member subobject, a base class subobject, or an array element.

[intro.object]

The storage duration of subobjects and reference members is that of their complete object

[basic.stc]

The members of the B object pointed to by myObj are all contained within that B object, and they all have the same (dynamic) storage duration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM