Memory allocation is done in 3 places
1. Static memory area
2. Stack - memory released when the var goes out of scope , no overhead
3. Heap - requires memory management , and overhead
eg. MyClass * mObj = new MyClass;
delete mObj;
Note : does automatic check for memory space existence before passing pointer to constructor.
New - creates memory space for object ANDD calls constructor malloc - creates only the mem space AND returns VOID*
Delete - frees the mem space AND calls the destrucctor free - only frees the mem space
int _tmain(int argc, _TCHAR* argv[]) { Test* t1 = new Test(); t1->Hello(); delete t1; Test* t2 = (Test*) malloc(sizeof Test); t2->Hello(); free(t2); return 0; }
Tip : After using delete its a good practise to set the poiinter obj to 0 since deleting a pointer second time
by mistake will not cause damage if the pointer points to 0..
Tip ( What happens when new does not allocate memory )
Beginning in Visual C++ .NET 2002, the CRT's new function (in libc.lib, libcd.lib, libcmt.lib, libcmtd.lib, msvcrt.lib, and msvcrtd.lib) will continue to return NULL if memory allocation fails. However, the new function in the Standard C++ Library (in libcp.lib, libcpd.lib, libcpmt.lib, libcpmtd.lib, msvcprt.lib, and msvcprtd.lib) will support the behavior specified in the C++ standard, which is to throw a std::bad_alloc exception if the memory allocation fails.