This is one of the fundamentals in C++.
Dynamic allocation
In your case, memory allocation and consequent constructor call for Z
will happen on new
:
Z* z = new Z();
The opposite part for destruction and memory deallocation will happen on delete
:
delete z;
But since your code don't have it, memory deallocation will never happen, plus you will lose the pointer z
having no possibility deallocating the object in future. This is typical memory leak.
Declaration
On the other hand, if you declare object like this:
Z z;
Memory allocation and constructor will be called immediately right here at declaration point, and when object's scope of existence is finished (i.e. at the end of the function) destructor will be called automatically and memory will be deallocated.
Dynamic allocation vs Declaration
I will not go into debates about what is better and what is not, but rather will provide the excerpt from one of the articles that is linked below:
Unlike declarations, which load data onto the programs data segment, dynamic allocation creates new usable space on the programs STACK (an area of RAM specifically allocated to that program).
FYI : Stack = Performance, but not always the best solution.
References
For your pleasure : tic tac toe.