When you write:
Test t; // object created normallytis created in stack memory (temporary memory).- It is automatically destroyed when the function (
main()here) ends. - This is called static allocation.
When you write:
Test *ptr;
ptr = new Test;-
new Testcreates an object in the heap memory (a large pool of memory managed at runtime). -
It returns the address of that object.
-
That address is stored in the pointer
ptr. -
Unlike stack objects, heap objects are not automatically destroyed when the function ends.
- You have to delete them yourself:
delete ptr; // frees memory| Static Object (normal) | Dynamic Object (new) |
|---|---|
| Created on stack | Created on heap |
| Lifetime: auto (destroyed when function ends) | Lifetime: manual (until delete) |
Accessed directly (e.g., t.in()) |
Accessed through pointer (e.g., ptr->in()) |
| Size fixed at compile time | Size decided at runtime |
Test t; // static → stack memory
Test *p = new Test; // dynamic → heap memorytexists only whilemain()runs.p’s object exists on heap until you explicitly free it withdelete p;.
So, dynamically creating an object means:
Making an object at runtime in the heap using new, instead of automatically on the stack.