Stack and Heap

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sunil9999
    New Member
    • Aug 2007
    • 1

    Stack and Heap

    How can we create an object directly on heap instead of getting the same created on stack? Pl anyone can help here on this!!!! Thanks a lot.
    Regards,
    Sunil
  • Meetee
    Recognized Expert Contributor
    • Dec 2006
    • 928

    #2
    Originally posted by Sunil9999
    How can we create an object directly on heap instead of getting the same created on stack? Pl anyone can help here on this!!!! Thanks a lot.
    Regards,
    Sunil
    Hi,

    (AFAIK) whenever any object is dynamically created it is stored in heap. For eg:

    Code:
    class A
    {
    A();
    };
    
    void fun(A * a)
    {
    a = new A();
    }
    Here the object a will be allocated in heap.

    Regards

    Comment

    • Girish Kanakagiri
      New Member
      • May 2007
      • 93

      #3
      Originally posted by Sunil9999
      How can we create an object directly on heap instead of getting the same created on stack? Pl anyone can help here on this!!!! Thanks a lot.
      Regards,
      Sunil
      In C, you can make use of malloc(), calloc(), realloc() functions to
      dynamically allocate memory so that they gets stored on heap.
      In C++ you can use new to dynamically allocate memory so that they gets stored on heap.

      Regards,
      Girish.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by Girish Kanakagiri
        In C++ you can use new to dynamically allocate memory so that they gets stored on heap.
        Be more firm about this:

        In C++ you must use new to dynamically allocate memory so that they get stored on heap.


        malloc() and free() do not call constructors or destructors so you can't use them in C++.

        Comment

        Working...