Thread: what is the difference btw heap and stack?

  1. #1
    Just kidding.... fnoyan's Avatar
    Join Date
    Jun 2003
    Location
    Still in the egg
    Posts
    275

    what is the difference btw heap and stack?

    What is the difference between creating an instance of a class in heap or in stack.
    Code:
      
            MyClass *clss = new MyClass(...);
            clss->someMethod();
      and
            MyClass clss(...);
            clss.someMethod();
    One of them is a pointer while the other is an instance of the class...

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Both are instances of the class. It's just that in the case of the heap, you also need to allocate a pointer on the stack to hold the address of the instance.

    The difference is in object lifetime. Objects on the stack are destroyed as soon as they go out of scope. Objects on the heap must be explicitely destroyed.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. stack and heap objects
    By John_L in forum C++ Programming
    Replies: 4
    Last Post: 03-18-2008, 10:20 AM
  2. stack vs heap memory allocation
    By gongchengshi in forum C Programming
    Replies: 9
    Last Post: 11-18-2007, 12:17 PM
  3. Relocatable code and Symbol Table
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 06-10-2002, 11:05 AM
  4. What is a Stack, Heap and Queue ?
    By pritesh in forum C Programming
    Replies: 3
    Last Post: 03-17-2002, 12:16 PM
  5. Stack and Heap
    By Barjor in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 01-29-2002, 09:11 AM