Pergunta

Possible Duplicate:
Does this type of memory get allocated on the heap or the stack?

class foo{
private:
int bar;
constructors and other members here...
}

If i create an instance of foo using the new operator where it will be created?

Heap i guess but where does my int bar; get created, stack or heap?

And if my bar wasn't a primitive data type but another object created like this->bar=bar();, where would it be created?

Foi útil?

Solução

Read about how class instances are constructed in the memory. Simple explanation here.

The members are a part of the class instance's chunk in memory. So where ever that class instance is allocated, the whole chunk is allocated, including the members.

Outras dicas

Since you have created foo in the heap all the member variables primitive/non-primitive will be in the heap too.

Case 1:

Foo *obj = new Foo();

bar is on the heap:

Case 2:

Foo obj ;

bar is on the stack:

according to the standard

3.7.4 Duration of sub-objects [basic.stc.inherit]

The storage duration of member subobjects, base class subobjects and array elements is that of their complete object (1.8).

Any automatic (not created with new) object/value is created inside its container object. If they are independent, they are created in the stack.

In this case, bar will be created inside its container object, which is the foo instance that was created in the heap. So bar will go to the heap, inside the foo instance.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top