Thread: Create generic classes to be specified later?

  1. #1
    C++ Enthusiast jmd15's Avatar
    Join Date
    Mar 2005
    Location
    MI
    Posts
    532

    Create generic classes to be specified later?

    I have a list of different classes that need to be created, but I won't know which classes or how many of each are in my list. So I was wondering if I could create an array of generic classes who's specific class could be defined later? Is that possible, or is there any other sort of workaround? Any suggestions pertaining to this is welcome, thanks.
    Trinity: "Neo... nobody has ever done this before."
    Neo: "That's why it's going to work."
    c9915ec6c1f3b876ddf38514adbb94f0

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I'm not sure what you mean? Are you writing code for these classes, or you are just going to write some code to CREATE the objects from some classes?

    --
    Mats

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Sounds like he wants something that utilizes reflection. Java might be better suited for this.

  4. #4
    C++ Enthusiast jmd15's Avatar
    Join Date
    Mar 2005
    Location
    MI
    Posts
    532
    Ok, well what I have right now is a bunch of classes already written, defined, all of them being child classes off of my main generic sprite class.
    Now, I'm reading in a file that has data that I parse and determine which of these classes that need to be initialized, and how many of each, but I'm not sure how I can initialize only the classes that I need, and only the amount that I need. It's sort of confusing, I hope I've clarified at least a bit. Thanks for the replies.
    Trinity: "Neo... nobody has ever done this before."
    Neo: "That's why it's going to work."
    c9915ec6c1f3b876ddf38514adbb94f0

  5. #5
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    I don't get the problem.

    Read from file. While data from file contains information on object, create object.

  6. #6
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    It sounds to me as if you want some kind of object factory. Have a look at the Factory Design Pattern and the Abstract Factory - this may give you some ideas (there are alot of variations on object factories.. some simple, some not so)

  7. #7
    C++ Enthusiast jmd15's Avatar
    Join Date
    Mar 2005
    Location
    MI
    Posts
    532
    While googling my problem I did come across the term Abstract Factory, so I'll go look those up and see if it's what I need.

    MacGyver:
    My problem is sort of hard to explain... but what I want to do is this:
    Read file. Parse data. Create generic objects. Set objects' classes to the ones specified in file. Set accompanying data to the classes.

    I'm trying to work over, in design, your simpler plan and see if I can get it to work. It seems like it should work but I'm coming across the problems of what containers to use, how to ONLY create the arrays I need, how to do this efficiently without loads of cases for a switch statement, how to know which arrays I actually did create in the end, etc.
    I don't know why this is stumping me, because it seems a trivial problem. But I think the problem I'm trying to describe is what wikipedia says for the Factory method pattern as "the problem of creating objects (products) without specifying the exact class of object that will be created."
    Last edited by jmd15; 08-04-2007 at 06:48 PM.
    Trinity: "Neo... nobody has ever done this before."
    Neo: "That's why it's going to work."
    c9915ec6c1f3b876ddf38514adbb94f0

  8. #8
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    There's no such thing as a "generic" object. you need to know the type of the object at the same time as you create it, because the object has all kinds of type information attached to it, including the size it occupies in memory - the size of the object cannot change.

    The Abstract factory can let you associate types with some identifier (such as a std::string or an int), then you can build concrete objects using the factory based on the type identifier which you read from your file. You can then store base-class pointers to these concrete objects in some sort of container, such as a std::vector.
    Last edited by Bench82; 08-04-2007 at 06:59 PM.

  9. #9
    C++ Enthusiast jmd15's Avatar
    Join Date
    Mar 2005
    Location
    MI
    Posts
    532
    Yeah, the Abstract Factory Method sounds like the ticket.
    What I have are three arrays. Two integer arrays, and one std::string array. The two integer arrays hold the x and y coordinates, and the string array holds the string identifiers for which class needs to be initialized with which coordinates, that way I can just grab one index number which (when plugged into any of the three arrays) will provide me with that one sprite's data. Now my next step is to turn these three arrays into actual created sprite objects, and I have all their classes written, I just don't know how to go about this.
    So this does sound like a case where the Abstract Factory Method would help me out to you?
    Trinity: "Neo... nobody has ever done this before."
    Neo: "That's why it's going to work."
    c9915ec6c1f3b876ddf38514adbb94f0

  10. #10
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    It sounds like a factory would fit the bill. There are all sorts of different ones possible. There should be plenty of material around the web which show various ways of automating the process. I suggest looking around to get an idea of whats involved (usually there is a "dictionary" involved somewhere, where the class identifiers are mapped on to some functors which actually create the object)

  11. #11
    C++ Enthusiast jmd15's Avatar
    Join Date
    Mar 2005
    Location
    MI
    Posts
    532
    Ok, I looked it up and I *think* I've implemented a very basic version.
    However, I have one problem, when I try to access a member function of the sub-class that's been created through the factory, it says that the base class doesn't have that function.
    Here's what I have:
    SpriteFactory.h
    Code:
    class SpriteFactory
    {
      public:
      virtual Sprite* getSprite(int)=0;
    };
    class ConcreteFactory : public SpriteFactory
    {
     public:
      virtual Sprite* getSprite(int x)
        {
          if(strcmp(sprname[x].c_str(),"EndPoint")==0)
    	  return new EndPoint(xsprcrds[x],ysprcrds[x]);
    
          if(strcmp(sprname[x].c_str(),"LeftCloud")==0)
    	  return new LeftCloud(xsprcrds[x],ysprcrds[x]);
    
          if(strcmp(sprname[x].c_str(),"LeftEndGreenBlock")==0)
    	  return new LeftEndGreenBlock(xsprcrds[x],ysprcrds[x]);
    
          if(strcmp(sprname[x].c_str(),"MidCloud")==0)
    	  return new MidCloud(xsprcrds[x],ysprcrds[x]);
    
          if(strcmp(sprname[x].c_str(),"MidGreenBlock")==0)
    	  return new MidGreenBlock(xsprcrds[x],ysprcrds[x]);
    
          if(strcmp(sprname[x].c_str(),"RightCloud")==0)
    	  return new RightCloud(xsprcrds[x],ysprcrds[x]);
    
          if(strcmp(sprname[x].c_str(),"RightEndGreenBlock")==0)
    	  return new RightEndGreenBlock(xsprcrds[x],ysprcrds[x]);
    
          if(strcmp(sprname[x].c_str(),"StoneBlock")==0)
    	  return new StoneBlock(xsprcrds[x],ysprcrds[x]);
        };
    };
    And here's how I use it in my main file:
    Code:
    	SpriteFactory* factory = new ConcreteFactory();
    	Sprite* test = factory->getSprite(0);
            ...
            test->draw();          //Get errors here
    Now, at the test->draw(); part that I get errors, I get the error:
    error: 'class Sprite' has no member named 'draw'
    but the draw member function IS in the subclass! It's not in the base Sprite class, but it's in the sub class!! So does anyone have any idea why this is happening?
    Thanks for the replies getting me this far, any further help's also appreciated.
    Trinity: "Neo... nobody has ever done this before."
    Neo: "That's why it's going to work."
    c9915ec6c1f3b876ddf38514adbb94f0

  12. #12
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    All the compiler sees is a Sprite.
    You might need some virtual functions.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  13. #13
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    And don't use that if-goulash. declare a std::map<std::string, pointer_to_constructor_of_special_class> and then add your classes like this:
    Code:
    sprite_ctor_map[RightCloud] = pointer_to_right_cloud_ctor;
    now instantiate sprites like this
    Code:
    Sprite* s = new sprite_ctor_map[RightCloud](ctor_arguments);

  14. #14
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Just a small observation: you are going through a lot of trouble to compare strings to literals in the C way, where it could be as simple as:
    Code:
    if (sprName[x] == "EndPoint")
    etc
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  15. #15
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    As someone else mentioned, you need to add a virtual (or a pure virtual) draw() function in sprite

    Assuming that sprname is an array or vector of C++ std::strings, you can simplify the if conditions to
    Code:
    if( sprname[x] == "EndPoint" )

    edit: I've only just noticed that someone pointed that out about five minutes before me
    Last edited by Bench82; 08-05-2007 at 09:06 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner Classes Question
    By kbro3 in forum C++ Programming
    Replies: 9
    Last Post: 08-14-2008, 07:43 AM
  2. Can you Initialize all classes once with New?
    By peacerosetx in forum C++ Programming
    Replies: 12
    Last Post: 07-02-2008, 10:47 AM
  3. Problem with classes.
    By kevinawad in forum C++ Programming
    Replies: 5
    Last Post: 06-26-2008, 09:33 AM
  4. VC++6: exporting classes containing templates
    By ttt in forum Windows Programming
    Replies: 2
    Last Post: 09-15-2003, 11:38 AM
  5. Question on use of classes
    By Flyer in forum C++ Programming
    Replies: 8
    Last Post: 06-25-2003, 08:23 AM