Thread: Object's array on the stack vs array on the heap

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Mar 2016
    Posts
    110

    Object's array on the stack vs array on the heap

    Is there any benefit to having this:

    OPTION 1:
    Code:
    class stackArray{    
    static const int STACK_SIZE = 3;
    public:
        stackArray(){
            item = new int[STACK_SIZE];
            item[0] = 100;
            item[1] = 101;
            item[2] = 102;
        };
        int *item;
    };
    over this:

    OPTION 2:
    Code:
    class stackArray{    
    static const int STACK_SIZE = 3;
    public:
        stackArray(){
            item[0] = 100;
            item[1] = 101;
            item[2] = 102;
        };
        int item[STACK_SIZE];
    };

    I would think that option 2 could cause dangling pointers but when I test it, it isn't the case. I tested option 2 with the following code:

    Code:
    stackArray createObject(){    
    stackArray instance1;
        return instance1;
    }
    
    
    int main (){
        cout << createObject().item[0] << endl;
        cout << createObject().item[1] << endl;
        cout << createObject().item[2] << endl;
        return 0;
    }
    And it printed out the array the same as option 1 with no garbage values.
    Last edited by Vespasian_2; 03-18-2019 at 01:02 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Static, Stack, Heap Array and time
    By 26friends26 in forum C++ Programming
    Replies: 3
    Last Post: 02-15-2011, 04:42 PM
  2. Deleting an array from the heap
    By DarkMasterBosel in forum C++ Programming
    Replies: 4
    Last Post: 01-08-2009, 12:13 AM
  3. Trying to Free Object On Heap As Array Throwing Debug Asserts
    By HyperShadow in forum C++ Programming
    Replies: 2
    Last Post: 06-19-2007, 10:05 PM
  4. C++ Object heap stack
    By vasanth in forum C++ Programming
    Replies: 4
    Last Post: 06-08-2006, 05:47 PM
  5. Managing a heap using an array.
    By rahuls in forum C Programming
    Replies: 3
    Last Post: 03-20-2003, 02:49 PM

Tags for this Thread