question about object instantiation

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • johny smith

    question about object instantiation

    Based on my experience there is two ways to instantiate an object.



    Method 1:



    Car* car1 = new Car();



    Method 2:



    Car car1;



    So, my question is what really is the difference in the two methods. Does
    one get stored on the stack while the other gets stored on the heap? Is one
    better than the other? How is one to reference the difference between the
    two, that is is the firt method called instantiation by ? while the second
    one is called instantiation by ?



    Any advice is greatly appreciated,



    John




  • Leor Zolman

    #2
    Re: question about object instantiation

    On Sat, 8 May 2004 17:21:41 -0600, "johny smith"
    <princetonharva rd@charter.net> wrote:
    [color=blue]
    >Based on my experience there is two ways to instantiate an object.
    >
    >
    >
    >Method 1:
    >
    >
    >
    >Car* car1 = new Car();
    >
    >
    >
    >Method 2:
    >
    >
    >
    >Car car1;
    >
    >
    >
    >So, my question is what really is the difference in the two methods. Does
    >one get stored on the stack while the other gets stored on the heap?[/color]

    Using "new" instantiates the object "dynamicall y"; the area of memory where
    the object is constructed happens to be called the "free store". The term
    "the heap" is often used synonymously (and purists around here would be
    happy to point out the differences), but those differences do not become
    important unless you insist on using library functions such as malloc and
    free to manage storage, rather than operators new and delete.

    When you do it the other way,
    Car car1;
    then the object may end up just about anywhere, depending on the context of
    that line of code. If it is a stand-alone definition at block scope or
    namespace scope, the object ends up in automatic storage (on the stack,
    usually), or static storage (a fixed location in memory, such as that
    occupied by all "extern" data), respectively. If, however, the line is
    part of a class definition, then it all depends on how the enclosing class
    is instantiated! for example, given:

    class Fleet {
    Truck truck1;
    Car loaners[10];
    Car car1;
    Bicycle b;
    };

    Then you might say:
    Fleet f1;
    Fleet *fleetp = new Fleet;

    In that case, f1 is automatic (in a block) or static (namespace scope), but
    the object pointed to be fleetp is dynamic (and contains a Car, among other
    things.)

    So as you can see, the question isn't as simple as you the one you asked.

    [color=blue]
    > Is one
    >better than the other?[/color]

    Sometimes one is better than the other for some particular purpose. Time to
    get yourself a good introductory C++ book and dive in.
    [color=blue]
    >How is one to reference the difference between the
    >two, that is is the firt method called instantiation by ? while the second
    >one is called instantiation by ?[/color]

    Because the non-dynamic one can appear in different contexts, I'm not sure
    how much good it would really do to label it instantiation by _____ . I
    just call it creating or instantiating an object, and when using "new" I
    add the word "dynamically".. .
    -leor

    --
    Leor Zolman --- BD Software --- www.bdsoft.com
    On-Site Training in C/C++, Java, Perl and Unix
    C++ users: download BD Software's free STL Error Message Decryptor at:
    An STL Error Decryptor for C++ by Leor Zolman of BD Software - available to download here

    Comment

    • Siemel Naran

      #3
      Re: question about object instantiation

      "johny smith" <princetonharva rd@charter.net> wrote in message
      [color=blue]
      > Method 1:
      > Car* car1 = new Car();
      >
      > Method 2:
      > Car car1;[/color]

      In addition to Leor's response, the 1st one invokes Car::operator new if
      such a function exists. This function may utilize a pool allocator. The
      entire pool of memory is created on the heap usually, so it is still heap
      allocation. You also have to call delete (though a smart pointer might be a
      good idea here).
      [color=blue]
      > So, my question is what really is the difference in the two methods. Does
      > one get stored on the stack while the other gets stored on the heap? Is[/color]
      one[color=blue]
      > better than the other? How is one to reference the difference between the
      > two, that is is the firt method called instantiation by ? while the second
      > one is called instantiation by ?[/color]

      As for names, how about instantiation by pointer and instantiation by value?
      Be aware these terms are not in common usage.

      For small objects like int, std::complex<do uble>, deque<T>::itera tor, it's
      probably faster and consumes less memory to create objects on the stack.
      For larger objects, it's faster too, but the ratio of time saved is usuall
      too small to worry about.

      And when you need polymorphism, you have to use the 1st way. For example,
      you have a class Database that holds a pointer to a Connection, but the
      Connection is a derived class like MySqlConnection , OracleConnectio n, etc.


      Comment

      • John Harrison

        #4
        Re: question about object instantiation


        "johny smith" <princetonharva rd@charter.net> wrote in message
        news:109qqrsluo choed@corp.supe rnews.com...[color=blue]
        > Based on my experience there is two ways to instantiate an object.
        >
        >
        >
        > Method 1:
        >
        >
        >
        > Car* car1 = new Car();
        >
        >
        >
        > Method 2:
        >
        >
        >
        > Car car1;
        >
        >
        >
        > So, my question is what really is the difference in the two methods. Does
        > one get stored on the stack while the other gets stored on the heap? Is[/color]
        one[color=blue]
        > better than the other? How is one to reference the difference between the
        > two, that is is the firt method called instantiation by ? while the second
        > one is called instantiation by ?[/color]

        The essential difference is the lifetime of the object.

        {
        Car* car1 = new Car();
        } // car1 is *not* destroyed here

        {
        Car car1;
        } // car1 is destroyed here

        Neither is better, they are just different. Objects allocated with new have
        an indefinite lifetime, they are only destoyed where you exlicitly use
        delete. This is undoubtedly more complicated but sometimes it is what you
        want.

        As a newbie if you cant see why you should use new then don't. The
        alternative is simpler.

        john


        Comment

        • JKop

          #5
          Re: question about object instantiation

          johny smith posted:
          [color=blue]
          > Based on my experience there is two ways to instantiate an object.
          >
          >
          >
          > Method 1:
          >
          >
          >
          > Car* car1 = new Car();
          >
          >
          >
          > Method 2:
          >
          >
          >
          > Car car1;
          >
          >
          >
          > So, my question is what really is the difference in the two methods.
          > Does one get stored on the stack while the other gets stored on the
          > heap? Is one better than the other? How is one to reference the
          > difference between the two, that is is the firt method called
          > instantiation by ? while the second one is called instantiation by ?
          >
          >
          >
          > Any advice is greatly appreciated,
          >
          >
          >
          > John[/color]


          There is far too much talk about "new" on this newsgroup! Where do these
          people learn to program?!! *This* is how you declare a variable/object:

          CarClass CarObject;


          In special circumstances, and only in special circumstances, you use dynamic
          memory allocation! Don't put chains on your tyres when there's no snow! It
          may help when there *is* snow, but without snow, ie. without the special
          circumstances, it just hinders everything!

          Here's a usage of "new":


          void GenerateStringO fMyName(unsigne d short int LengthOfName)
          {
          //Create an array of characters, the length of the person's name + 1
          for the terminating null charachter

          char NameBuffer[LengthOfName + 1];

          //Long story short, the above is invalid - the amount of memory
          allocated for each function must be constant!

          //So you do the following:

          char* pNameBuffer = new char[LengthOfName +1];

          //Do some stuff

          delete [] pNameBuffer;
          }


          You should very very rarely use "new", and even more rarely if you're not
          declaring an array! Think about it, why the heck would you?!


          -JKop

          Comment

          • jeffc

            #6
            Re: question about object instantiation


            "johny smith" <princetonharva rd@charter.net> wrote in message
            news:109qqrsluo choed@corp.supe rnews.com...[color=blue]
            > Based on my experience there is two ways to instantiate an object.
            > Method 1:
            > Car* car1 = new Car();
            >
            > Method 2:
            > Car car1;
            >
            > So, my question is what really is the difference in the two methods. Does
            > one get stored on the stack while the other gets stored on the heap?[/color]

            Method 1 heap, Method 2 stack.
            [color=blue]
            > Is one better than the other?[/color]

            Method 2 is better because the memory that is allocated gets automatically
            deleted.
            [color=blue]
            > How is one to reference the difference between the
            > two, that is is the firt method called instantiation by ? while the second
            > one is called instantiation by ?[/color]

            Method 1 is dynamic allocation. Method 2 is static or automatic allocation.
            Use method 2 whenever possible and practical. Use Method 1 only when you
            have no choice (you don't know ahead of time if you will need that memory,
            etc.)


            Comment

            • jeffc

              #7
              Re: question about object instantiation


              "JKop" <NULL@NULL.NULL > wrote in message
              news:YaJnc.7338 $qP2.15408@news .indigo.ie...[color=blue]
              >
              > You should very very rarely use "new", and even more rarely if you're not
              > declaring an array! Think about it, why the heck would you?![/color]

              Umm, because you're writing an Object Oriented programming exploiting
              polymorphism? If you "very very rarely" use "new", then you don't write a
              lot of Object Oriented code. C++ *is* an Object Oriented language,
              remember?


              Comment

              • Siemel Naran

                #8
                Re: question about object instantiation

                "JKop" <NULL@NULL.NULL > wrote in message news:YaJnc.7338
                [color=blue]
                > void GenerateStringO fMyName(unsigne d short int LengthOfName)
                > {
                > //Create an array of characters, the length of the person's name + 1
                > for the terminating null charachter
                >
                > char NameBuffer[LengthOfName + 1];
                >
                > //Long story short, the above is invalid - the amount of memory
                > allocated for each function must be constant![/color]

                I think the feature is present in standard C, and standard C++ should
                eventually follow suit. Maybe someone else can comment.

                [color=blue]
                > //So you do the following:
                >
                > char* pNameBuffer = new char[LengthOfName +1];
                >
                > //Do some stuff
                >
                > delete [] pNameBuffer;[/color]

                Here's another reason not to use raw pointers -- if the "Do some stuff"
                throws then pNameBuffer is never released. If you use

                std::vector<cha r> pNameBuffer(Len gthOfName + 1);

                you're safe. So a guideline is that every use of new should use wrapped in
                a smart pointer, be it std::vector<T> or std::auto_ptr or boost::shared_t pr,
                so that we always destroy the object.

                But when we allocate objects on the stack, we don't have to worry about
                this. Plus, access to the member variables of objects on the stack is
                usually faster (especially inline functions).
                [color=blue]
                > You should very very rarely use "new", and even more rarely if you're not
                > declaring an array! Think about it, why the heck would you?![/color]

                Generally I create factory/create functions which call new and return a
                std::auto_ptr. The rest of the code hardly ever uses new and delete.


                Comment

                Working...