CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2009
    Posts
    2

    Instantiate objects dynamically from an array of classes

    Basically, I want to create a series of objects dynamically in an arbitrary order. If I have Class1 and Class2 that both inherit from BaseClass, I want to do something like this: (obviously this will not function, but I think you'll get the point)

    Code:
    class list_of_classes[3] = {Class1, Class2, Class1};
    int class_num = 0;
    
    BaseClass * someObject = new list_of_classes[class_num];
    
    void CreateNextClass()
    {
    delete someObject;
    someObject = new list_of_classes[class_num];
    class_num++;
    }
    To give some context, I am building a game where Class1, Class2, etc... are types of levels, and I want to be able to load the levels in an arbitrary order. I understand that I could just create an array of objects at compile time and cycle through them at run time, but this doesn't seem very efficient as the number of levels increases, nor does it seem object-oriented. Is there a way to do this, or do I need to take an entirely different approach? Thank you so much for any advice.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Instantiate objects dynamically from an array of classes

    You could use a factory pattern, eg:

    Code:
    BaseClass *CreateLevel(int type)
    {
        switch(type)
        {
        case 0:
            return new LevelType0;
        case 1:
            return new LevelType1;
        // etc
    }

  3. #3
    Join Date
    Jul 2009
    Posts
    2

    Re: Instantiate objects dynamically from an array of classes

    Ah, so that's what factory patterns are That looks like a pretty good solution. I'd prefer not to have to edit the factory just to add a new type of level, but this is at least more encapsulated than my current solution. Thanks for the tip.

  4. #4
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Instantiate objects dynamically from an array of classes

    Have a look at typelists. You'll probably want to get a hold of a copy of 'Modern C++ design' for some explanation.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured