Sunday, August 2, 2009

How can you create an object from a class without knowing the class name in C++?

I'm making a game using C++. The game will load levels from a file but I don't know how I will create an object from a class that gets the class's name from the file with the data to create the level.

How can you create an object from a class without knowing the class name in C++?
It does not matter if you have the information in a text file or a binary file, this will be up to you.





Anyhow, what you could do is create a struct or class that will have the features needed for a level. It will need a "name" field, so you can set the name as required. You should include as much as you can, even if it means creating more classes struct that are referenced or pointed (better) to in the struct/class.





When you load the file in, you create one of these new structs/classes and add the details as needed. This may be easiest done by overwriting the input and output operators %26gt;%26gt; and %26lt;%26lt; Then when you save the class/struct, it will be saved in the manner that you ned it, and can be read it more easily. All levels can be saved in the same file if you want to open/create all at once. Otherwise, you could have seperate files for each level, readin in and creating only when needed.





If this is not what you meant, and you meant about the file you read in will have random classes associated with it.





Then what you do, if you own the classes that need to be created, is to overwrite the input and output operators, as mentioned above, and save and read in the data of the classes needed into/out of the file.
Reply:This site will probably give you much better answers since it's only for programming. I use it a fair amount and the answers are always helpful. Check it out:


http://cboard.cprogramming.com/
Reply:That's a tough one, in short, you can't, this only can be done in a frameworked language like Java or type-less prototypical language like VB and JavaScript. C++ has no built-in support for what you ask for.





Investigate add-on frameworks like Microsoft Foundation Classes or Trolltech QT or others.


No comments:

Post a Comment