Thread: Class Question

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    8

    Question Class Question

    What is the difference in doing:

    Code:
    MyClass x;
    
    x.function();
    vs.

    Code:
    MyClass x = new MyClass();
    
    x->function();
    and what is the reason for using one method over the other?

    Any help is appreciated.

    Thanks.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The difference is that the first one exists and the second one doesn't. You can make the second one work by doing
    Code:
    Myclass *x = new MyClass();
    x->function();
    The idea being is that x is not an object itself, it merely points to some other object that already exists (or in this case, is created at the time).

    Having pointers allows for polymorphism, as you can see by the other top five threads in the forum today.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Generally you should prefer the first method over the second unless you have a specific reason to use the second (like polymorphism as tabstop said).

    In addition, the second example is missing an important part- the delete. You have to delete anything you allocate with new, which is a big reason why the first method is preferred in the simple case.

    Finally, for occasions where you want to use the second version, it's generally a good idea to get in the habit of using smart pointers so that you don't forget to delete the memory and destroy the object you allocated and so it gets cleaned up automatically like the first version.

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    8
    Thanks, ... and I meant to put *x

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM
  2. Replies: 8
    Last Post: 10-02-2005, 12:27 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. question about DLL's and class functions
    By btq in forum Windows Programming
    Replies: 2
    Last Post: 02-25-2003, 06:08 AM
  5. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM