Before object creation, let's understand the fact that a computer program has both a stack and a heap.
What is the stack? It's a special region of your computer's memory that stores temporary variables created by each function (including the
main() function). The stack is a "FILO" (first in, last out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is "pushed" onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.The advantage of using the stack to store variables, is that memory is managed for you. You don't have to allocate memory by hand, or free it once you don't need it any more.Another feature of the stack to keep in mind, is that there is a limit (varies with OS) on the size of variables that can be store on the stack. This is not the case for variables allocated on the heap.
Unlike Java, in C++ objects can also be created on the stack.
For example in C++ you can write
Class obj; //object created on the stack
Class obj=new Class(); //If you need to create the object in the heap in C++
In Java you can write
Class obj; //obj is just a reference(not an object)
obj = new Class();// obj refers to the object
Therefore it is clear that C++ differs from Java with the ability it has to create objects in the stack.If you do not create the objects in the stack in C++, then you will have to manually manage the memory each object owns. Which means once the object is no longer needed, you have to free the memory it had owned. This is because C++ does not have a garbage collector built into the language ( although third party garbage collectors are available ). In Java there is no need to manually manage the memory ( it has a garbage collector built in).
No comments:
Post a Comment