I'm trying to translate some projects I've made with Delphi; an object can be declared in general as:
//I have the control of the object and I MUST delete it when it's not needed anymore
male := THuman.Create();
try
// code
finally
male.Free; (get rid of the object)
end;
Reading Stroustrup's book about C++ I have understood that (in short) his language doesn't need the finally
block because there are always workarounds. Now if I want to create a class I have two ways:
THuman male;
in which the object is created and then goes out of scope when the block{... code ...}
endsTHuman* male = new THuman
I can control the object's life and destroy it with adelete
The book suggests to use the first approach (even if both are fine) but I come from a Delphi background and I want to use the second method (I have the control of the object).
Questions. I cannot understand the difference between the 2 methods that C++ have for objects and reading online I got more confusion. Is it correct if I say that method 1 allocates memory on the stack and method 2 on the heap?
In method 2 (we're in the heap) if I assigned the value NULL
to the object, do I still have to call the delete?
For example Delphi allows to create instances only on the heap and the Free
deletes the object (like delete
in C++).