Hello all,

My understanding is that the Objects created are stored in the heap segment.

What if the objects are created for a class with static data members?
Do the static data alone reside in the data segment, while the rest of the members are allocated on the heap?

I read somewhere the following
(when object is created inside a block in the main fn):

"When the block is exited, an object's destructor gets called (because objects on the stack are destroyed automatically when their scope ends)". This implies that the object contents are stored on the stack.

Could someone resolve this contradiction?

I think everything is stored on the stack unless you specifically do some kind of dynamic allocation using new or malloc() or something similar.

My understanding is that the Objects created are stored in the heap segment.

Your understanding is incorrect. The location for an object depends on how it's created.

What if the objects are created for a class with static data members?

The static data members are stored separately from instance data members. Since you mentioned the heap segment, I'll assume a certain common executable format and say that if the static data member is initialized, it goes in the data segment, and if it's uninitialized, it goes in the BSS segment. Instance data members will depend on how the object is created. If it's dynamically allocated such as with new, then you're likely looking at the heap segment, though that's not guaranteed.

Your understanding is incorrect. The location for an object depends on how it's created

Could you please elaborate Narue? :)

Without putting too fine a point on it, local objects are stored on the stack and dynamically allocated objects are stored on the heap:

class foo { int x; }

int main()
{
    foo bar; // bar is stored on the stack
    foo *baz; // baz is stored on the stack

    baz = new foo; // *baz is stored on the heap

    // Necessary because *baz isn't released on scope exit
    delete baz;
}

It can get more complicated, but that should serve as an example of how the location in memory depends on how an object is created.

commented: Clear explanation with example :) +1

sorry about that.. wrong window:">

Thanks Narue! That was wonderfully put!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.