Dyn class/object creation

Started by
2 comments, last by chbfiv 20 years, 6 months ago
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]
-BourkeIV
Advertisement
A std::vector may be right up your alley.

http://www.sgi.com/tech/stl

How appropriate. You fight like a cow.
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.
You don't need to vote for the "lesser of two evils"! Learn about Instant Runoff Voting, the simple cure for a broken democracy!
I should have come up with that; I just dont use them much, yet=) thanks both of you.
-BourkeIV

This topic is closed to new replies.

Advertisement