Hi all,
I have a question about the 'new' keyword. I couldn`t understand the difference between defining an object and creating an object by 'new' keyword.
CClass myClass;
CClass myClass = new CClass;
What`s the difference, or is there a difference.
Printable View
Hi all,
I have a question about the 'new' keyword. I couldn`t understand the difference between defining an object and creating an object by 'new' keyword.
CClass myClass;
CClass myClass = new CClass;
What`s the difference, or is there a difference.
CMyClass *pmyClass = new CMyClass;
new creates the object on the heap, so it isn't destroyed when the object leaves scope. That is useful in a lot of situations. (But I won't list them now)
Thanks CornedBee,
And in that case, do you mean polymorphism or inheritance with
'lots of situations'. I`d like to know the advantages of 'new', please.
I mainly mean object persistence. Say you have a linked list, you might want to store pointers instead of the whole objects. If you do
CClass class;
list.Add(&class);
the list will have an invalid pointer once the function that called Add returns. If you do
CClass* pClass = new CClass;
list.Add(pClass);
you will have a valid pointer until you call delete.