4

In C# classes are stored in heap, and structs are stored in stack.

Does in C++ classes and strucs are stored in the same way (assuming I create my classes and structs statically, and every member of class or struct is not allocated by new) ?

Please explain this using snippet of code below:

class B
{
int b;
}

class C
{
int c;
}

class A
{
B b;
C c;
int x;
}

struct SB
{
int sb;
}

struct SC
{
int sc;
}

struct SA
{
SB sb;
SC sc;
int x;
}

void main()
{
A a1;
A *a2 = new A;

SA sa1;
SA *sa2 = new SA;
}
Vadim
  • 1,223
  • 2
  • 17
  • 26
  • 2
    "*In C# classes are stored in heap, and structs are stored in stack.*" - Not completely true and overly simplistic, see [this article](http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx) – Ed S. Aug 26 '11 at 20:21
  • Thank for the article! Will read it. – Vadim Aug 26 '11 at 20:30
  • Given your code example, it's impossible to say where *anything* is stored, since you haven't declared or otherwise created any objects. An object of type SA will *contain* objects of type SB, SC, and int, all of which will be stored as part of the containing object. Where that object is stored depends on how it's created. – Keith Thompson Aug 26 '11 at 21:07
  • Actually I have declared them, scroll down a bit, there is also function main in which they are declared. Also please see my comment under Keith Thompson answer (which I accepted), reading answers I have written my point as how they are stored, please say whenever I'm right or not. – Vadim Aug 26 '11 at 21:18

5 Answers5

7

There is no (necessary) difference in how structs are stored vs. how classes are stored. In fact, the only difference between structs and classes in C++ is that struct members are public by default, and class members are private by default.

Like any other kind of object, an object of class or struct type has a storage duration which is determined by how it's created.

An object declared inside a function has its lifetime limited to the enclosing block; this is typically implemented by storing it on the stack.

An object declared outside a function, or with the static keyword, has a lifetime that extends over the entire execution of the program; this might be implemented by storing it in the data segment.

An object allocated by a new operator (or malloc() call) exists until it's deleted (or free()ed); such objects are allocated in the "free store", sometimes informally referred to as "the heap".

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • 2
    You got that backward: class members are private by default, struct members are public by default so that the struct keyword maintains compatibility with C. – Rob K Aug 26 '11 at 20:27
  • 2
    Since you preferred being so pedantic in comments, you should follow the same in this answer. You should be saying Freestore not Heap. – Alok Save Aug 26 '11 at 20:30
  • Thanks, you're right of course. (I knew that, I just mistyped it.) Fixed. – Keith Thompson Aug 26 '11 at 20:30
  • @Als: I said it's *typically* implemented using a heap, and that is a very common term for it. I see the standard does use the term "free store" (two words). It also has a section on "Heap operations", but that's using the term to refer to a particular kind of data structure, not the common term for the free store. Ok, I'm convinced, I'll update my answer. – Keith Thompson Aug 26 '11 at 20:36
  • @Als - Keith's comment made a perfectly valid point -- the first line in your answer can be confusing since it answers a different question. No need to get defensive. – Dawson Aug 26 '11 at 20:41
  • @Toolbox: I think we could sort it out ourselves without an referee or mediator, Thank you. – Alok Save Aug 26 '11 at 20:44
  • Think I uderstand now. I updated the first post a bit, and as far as I understand: a1 (and it's members) is stored in the stack, a2 (and it's members) is stored in heap. Same for structs: sa1 is stored in stack, sa2 is stored in the heap. Right? – Vadim Aug 26 '11 at 21:02
3

The code that implements Classes/Structures (i.e., the code that implements the types) are stored somewhere in the code segment.

EDIT:
As OP clarify's in the comments, The answer to his Question, starts from below here. There was an ambiguity in the Q, which lead to the opening statement of this answer.

Depending on how you create your objects, they are created on dynamic storage(freestore) if created with malloc,new or are created on local stack storage.

Also, it depends on where objects are created.
Globally scoped objects & static objects are created on Data segment or BSS segment.

AFAIK the C++ standard does not mention of the memory segments(except freestore(aka heap) and local storage(aka stack)). So actually rest is an implementation detail.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 1
    I'm not sure what you mean by "Classes are stored somewhere in the code segment". Are you referring to the code that implements the class? An *object* of class type won't be stored in the code segment (unless perhaps it's a constant whose value can be determined at compile time). – Keith Thompson Aug 26 '11 at 20:25
  • Or they could be on the heap if you use `malloc` and placement new :) – Seth Carnegie Aug 26 '11 at 20:25
  • @Keith Thompson: Ofcourse I mean the code that implements the class. – Alok Save Aug 26 '11 at 20:26
  • @Seth Carnegie: To be minutely pedantic, placement new can allocate a memory that is not on freestore. – Alok Save Aug 26 '11 at 20:27
  • @Als actually placement new doesn't allocate memory does it? – Seth Carnegie Aug 26 '11 at 20:30
  • @Seth Carnegie: :) It doesn't it just points the preallocated memory to an pointer, that preallocated memory need not be on freestore, Is what i meant to indicate. – Alok Save Aug 26 '11 at 20:31
  • @Als: Ok, but that's obviously not what the OP meant by "In C# classes are stored in heap"; he meant objects of class type. – Keith Thompson Aug 26 '11 at 20:39
  • @Keith Thompson: Does the answer not explain, what OP wants, or am i missing something? – Alok Save Aug 26 '11 at 20:45
  • @Als: Yes, it does answer the question. I just thought that "Classes/Structures are stored somewhere in the code segment" wasn't particularly relevant. The OP didn't state the question precisely. On the other hand, the unqualified term "structs" most likely refers to struct *objects* rather than struct *types* (unless "classes", which IMHO should always refer to class *types*). – Keith Thompson Aug 26 '11 at 21:05
  • @Keith Thompson: Thats fine. The Q itself has that ambiguity, And just to be frank I am not that pedantic, So apologies if you feel I was rude or offending i didn't intend to, just one of those days where most people are rubbing me the wrong way. – Alok Save Aug 26 '11 at 21:08
  • Als, Keith Thompson: sorry for some ambiguity, I mean class objects, and struct objects, see first post. – Vadim Aug 26 '11 at 21:11
  • @Als: No problem. I think we've managed to get all the relevant information out there, which is the important thing. (Incidentally, I know C better than I know C++; that probably influences my answers a lot.) – Keith Thompson Aug 26 '11 at 21:12
1

afaik, classes / structs initialized without using the "new" operator are stored on the stack, and those created using "new" are on the heap.

Matthew
  • 24,703
  • 9
  • 76
  • 110
0

C++ has three allocation classes: automatic, dynamic, and static, connected to object lifetime (respectively scoped, manual and permanent). Typically, automatically allocated objects are implemented as being placed on the stack, while dynamically allocated objects go onto the heap; together, stack and heap comprise the "stack segment" of the program. The program also (typically) has a "data segment", which is where statically allocated objects go -- think of static allocation as happening at load time, so that memory is set aside before the program proper even begins. The data segment may contain read-only parts, which is where you might find some of your string constants (so don't write to them).

All these are implementation details, of course, and none of this is mandated by the language. It's just a popular implementation on desktop platforms.

So whether something is a class or a struct or an int, that's irrelevant, what matters is how you allocate it.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
-1

When classes or structs are created automatically, they are stored on the stack. When they are created dynamically, they are stored in the heap.

Daniel
  • 6,595
  • 9
  • 38
  • 70
  • 2
    I very much question that. Static objects (i.e. globals) are created in statically (load-time) allocated memory, which is different from the stack. – Kerrek SB Aug 26 '11 at 20:24
  • @Kerrek: I was talking about creating objects using static memory allocation (e.g. `int a[5];`) vs. dynamic memory allocation (e.g. `int *a = new int[5];`. I was not talking about static objects – Daniel Aug 26 '11 at 20:40
  • not clear what your context is, in the global scope, `int a[5];` is statically allocated, while in local scope `int a[5];` is simply *not* static allocation. – Kerrek SB Aug 26 '11 at 20:41
  • @Kerrek: Please see the accepted answer to [this question](http://stackoverflow.com/questions/2672085/c-static-array-vs-dynamic-array) – Daniel Aug 26 '11 at 20:42
  • Unfortunately the word "static" is heavily overloaded in C++, in all meanings of the word "overloaded". What you have is an automatically allocated static array. Nonetheless, it is still an automatic variable, not a static one. – Kerrek SB Aug 26 '11 at 20:57
  • @Kerrek: I am aware that it is an automatic variable. Why is that relevant? – Daniel Aug 26 '11 at 21:02
  • because your answer says "when classes are created statically". It should say "automatically". Also, when you use `new` you still have no idea where the object goes, I could have replaced the new operator with something that takes the memory from a local memory buffer on the stack... :-) – Kerrek SB Aug 26 '11 at 21:04
  • @Kerrek: Fair enough. I have edited my answer (although the thing about replacing the new operator is a big nit-pick) – Daniel Aug 26 '11 at 21:10
  • Cheers. Yeah, it's a bit pedantic, but it's important to realize that in C++, object lifetime and allocation implementation details are separate, orthogonal concepts; especially for a recovering C# victim such as the OP :-) (I didn't downvote you, by the way.) – Kerrek SB Aug 26 '11 at 21:13
  • @Kerrek: Just because languages like C# and Java are a million times more user friendly than C++, doesn't mean that their users are "victims" :-) – Daniel Aug 26 '11 at 21:21
  • You're right, I was being facetious. Unfortunately it is my experience that a lot of C#\Java programmers often try to reason about things like "stack" and "heap" and refer to half-truths about which those languages by design do not make you think quite as well as C++ does -- there've been many such questions before here :-) I hope you pardon the occasional pun! – Kerrek SB Aug 26 '11 at 21:53