Results 1 to 4 of 4

Thread: Using 'new' keyword for creating objects

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Apr 2002
    Posts
    20

    Using 'new' keyword for creating objects

    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.

  2. #2
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    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)
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Apr 2002
    Posts
    20
    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.

  4. #4
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    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.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width