It is said in Stroustrup
"An object constructed by explicit or implicit use of a constructor is automatic and will be destroyed at the first opportunity (see ยง10.4.10)."
So if i define a new object of any class using a new function.
Will it still be considered automatic and be deleted ?
or would it be saved in the heap such that it will be deleted only using delete
command ?
className objName = new(className); //this is what i have in mind.
What you have there is incorrect; you want classname* instead.
That said, objName is automatic and will be destroyed. The memory you have allocated on the heap with new, however, will be left there and you will have a memory leak unless you have deleted it.
And yeah i understand what you are saying. thanx a lot.
So, do i have to make sure I delete the variable before I go out of scope ? or can i delete this at the end when program is exiting ?
Also, what exactly happens when we say there is a "memory leak"
A memory leak means that you new'd some memory and then not delete'd it before you lost all pointers to it. As a result, you have memory sitting, unusable but that the OS still has given you ownership of.
delete it whenever you are finished with it. Just make sure you have a pointer to it so you can do that. Remember, the pointer and the data itself are different, so don't think you are "deleting the pointer". You are using the pointer to free the memory you have allocated with new.