In the C++ programming language, instances of the native data types, as
of the user defined data types,
can be created on the stack automatically when their visibility scope is entered, and are automatically
destroyed when the scope is left (i.e. when the } closing brace
of the block is reached):
if(...) {
int i; //i created on the stack
car c1;//c1 created on the stack
…
} //i and c1 both go out of scope and are
destroyed
alternatively, objects (and instances of the native data types) can be
allocated dynamically using new, in which case it is responsibility of the programmer
to destroy them when they are no
longer needed using delete:
int *ip;
car *cp;
ip = new int(3);//mem allocated for an int and
initialized to 3
cp = new car;//mem allocated for a car object
...//ip now stores the address of the initialized area
where
...//the “3” integer is stored
delete ip; delete cp;//this frees up the memory
Please note that memory is not freed up for objects allocated with new until the end of the program unless you explicitly call delete.