0

Possible Duplicate:
When should I use the new keyword in C++?

I don't know the difference between case 1 and case 2:

I define a struct below:

struct Graph {
    int ID;
}

Case 1:

Graph g;
g.ID = 1;

case 2:

Graph* g = new G();
g.ID = 1;

Are these two cases the same? What's the difference?

1
  • 1
    If a semicolon is added at the end of the struct definition, then case 1 may compile. Feb 28, 2012 at 16:12

4 Answers 4

3

In case 1, the memory used by g is allocated on the stack, which means that it will be automatically freed when the function it is in returns.

In case 2, the memory used by g is allocated on the heap, which means that it will only be freed when explicitly deleted using the delete operator.

Also, in case 2 since g is a pointer, you should be accessing fields of g using the -> operator:

g->ID = 1;
1

In case 2 you mean new Graph and then g->ID = 1. Try starting from http://en.wikipedia.org/wiki/New_(C%2B%2B) . Short story, case 1 allocates memory at compile time, while case 2 allocates it at run time.

1

The difference is where the data is allocated.

In Case 1, the data for your Graph struct is allocated on the stack. You access it via the name "g".

In Case 2, the data for your Graph struct is allocated on the heap. You access it via a pointer to that data, which is held via the name "g".

1

In case 1, you are creating the Graph on the stack, within the local scope. Thus it will automatically get deleted when the scope ends. g is thus an actual instantiated version of that Graph.

In the second case, you are allocating the Graph on to the heap. g is then only a pointer and will not be deleted until you explicitly do so.

3
  • HEap and Stack are not usefull concepts in this context. The terms you are looking for are automatic storage duration and dynamic storage duration. The problem with Heap and stack is that things get confusing when you have members of an object that has been dynamically allocated. The dynamically allocated object has dynamic storage duration while its members (if not pointers) are automatic storage duration (even though the members are on the heap) and will be correctly cleaned up when the object is destroyed. Feb 28, 2012 at 16:17
  • Sure, it is not of much practical use but when you get one of those programming tests in a job interview they are sure to ask you what the difference between the heap and the stack is, so it is as well to know! Feb 28, 2012 at 16:25
  • Yes it is great comp Sci thing to know (and you should know the difference). But it is not us-full when explaining C++ concepts. Feb 28, 2012 at 16:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.