Archived

This topic is now archived and is closed to further replies.

chbfiv

Dyn class/object creation

Recommended Posts

Maybe someone can give me some other methods that might be dynamic instead of static for basic class creation.
#define MAX_OBJECTS 1000

class Foo {
public:
    Foo() {
        for(int i = 0;i < MAX_OBJECTS;i++)
            bars[i] = NULL;
    }
    ~Foo() {
         for(int i = 0;i < MAX_OBJECTS;i++) {
             if(bars[i])
                 delete bars[i]
         }
    }
    Bar *bars[MAX_OBJECTS];
    void create_bar() {
    bars[num_bars] = new Bar;
    num_bars++;
    }
private:
    int num_bars;
};

class Bar {
    int whatever;
};
I would rather have limitless objects then limited objects. [edited by - chbfiv on October 6, 2003 12:45:47 PM] [edited by - chbfiv on October 6, 2003 12:46:58 PM]

Share this post


Link to post
Share on other sites
Dynamically allocate them instead. When you want to use more elements than exist in your previous array (array A), create a new array (array B), with slightly larger size, copy the contents of A into B, delete A, and replace A with B.

The following is valid syntax:

Bar * bars;
bars = new Bar[someintegervariable];
// (do whatever)
delete [] bars;

You could also implement a pattern such as a linked list, where each element in the list is like a link of a chain, with knowledge of the next element in addition to its own data. You can add or remove links from the chain whenever you want.

Share this post


Link to post
Share on other sites