What is hapening here:
I can declare a pointer to cls1 and I can access (set) the cls1 object without 'new' operator?! Why?
MyClass cls1;
MyClass* pCls1 = &cls1;
pCls1->set(int i);
pCls1->printAll();
delete pCls1;
What is hapening here:
I can declare a pointer to cls1 and I can access (set) the cls1 object without 'new' operator?! Why?
MyClass cls1;
MyClass* pCls1 = &cls1;
pCls1->set(int i);
pCls1->printAll();
delete pCls1;
Last edited by djddj; 11-09-2006 at 12:30 PM.
>Why?
Why not? pCls1 points to a valid object. I hope someone didn't tell you that pointers have to be used with new and delete. That person is woefully misinformed.
>delete pCls1;
This, on the other hand, is very bad. pCls1 points to cls1, so using delete will try to free the memory allocated to cls1. However, since cls1 wasn't allocated using new, the behavior is undefined. With any luck it'll crash immediately and leave a nasty message in your face so that you can fix it.
My best code is written with the delete key.
Originally Posted by Prelude
Thank you for reply!
That's right with the error message.
Ok, pCls1 points to a valid object that has its own memory. Why can not use delete for deleting pCls1? I know, if i using 'new' it works, but what is the background, I can delete only objects stored in heap, right?
Last edited by djddj; 11-09-2006 at 12:45 PM.
>Why can not use delete for deleting pCls1?
The simple explanation is that you can't delete memory that you didn't allocate with new.
My best code is written with the delete key.
check out some tutorials if you need help understanding dynamic memory and when its used
http://www.cplusplus.com/doc/tutorial/dynamic.html