Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

new keyword??

Options
  • 13-02-2003 12:48pm
    #1
    Closed Accounts Posts: 18


    Hello there,

    I have a question, I'm using a class in my program (which is a flight simulator) and I'm declaring an object of the class as follows;


    Aeroplane Theplane;

    Aeroplane is the class name and Theplane is the name of the object.

    What is difference between declaring it as follows:


    Aeroplane *Theplane;
    Theplane =new Aeroplane();


    What exactly does the new keyword do, and do I need to use it???

    Thanks in advance.


Comments

  • Registered Users Posts: 15,443 ✭✭✭✭bonkey


    The new keyword is what causes a new instance of type Aeroplane to be created.

    So yes, you probably do need it somewhere.

    jc


  • Closed Accounts Posts: 9,314 ✭✭✭Talliesin


    Java or C++?

    Slightly different usage in either. It should be in chapter 3 or earlier of any beginners book.

    It looks like C++ (but maybe you're trying to learn both at the same time and getting them mixed up, learning similar languages simultaneously can easily cause that).
    Briefly the first creates an object on the stack, it will be cleared up when the variable goes out of scope. It is generally less error-prone, and more efficient (in particular some stuff can be inlined in this case that can't be inlined with pointers).
    The second contains a pointer on the stack, that points to somewhere else. It can point to an object created on the stack previously, or one created on the heap with new.
    new creates a new object that won't go out of scope (though if the only pointer to it does you can will never use that memory again unless you have some sort of garbage collection going).
    delete uncreates such an object and releases the memory used.

    An important thing about pointers is that they can point to objects of derived classes, so Theplane = new JetPlane(); would be allowed if JetPlane had Aeroplane as a public base.

    There's more to read up on on this one. References are another thing you need to know, but it's something you need to know inside-out and back-to-front, so get reading.


  • Closed Accounts Posts: 867 ✭✭✭l3rian


    http://www.codeguru.com/cpp/tic/tic0135.shtml#Heading363

    free online c++ book, that link is to the section on the keyword new


Advertisement