Creating a class object on run time in C++

Started by
6 comments, last by GameDev.net 17 years, 11 months ago
Hi, Is it possible to use RTTI to create a class object at runtime - like for example do something like Class obj = something("CLASSNAME").getClass(); ? I know I can do it by using a function which returns the class based on the string but does a thing already exist like something like typeid(name).getClass(); ?? Thanks
The more applications I write, more I find out how less I know
Advertisement
[edit] I hadn't read your entire post. I don't think that what you are thinking of is possible in C++ (I assume this is C++).[/edit]
You can do it using something called the factory pattern. Loki has an implementation.


jfl.
I dont' believe there is a built-in C++ function for that. You'll have to resort to a factory of some flavor.
Quote:Original post by CRACK123
I know I can do it by using a function which returns the class based on the string
No, you can't. In C++ classes are not objects that you could return from a function.

If you're using the .NET framework, you can do this using code emission within the reflection namespace.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconemittingdynamicassemblies.asp

However, I'm not sure if you can do this in managed C++.

Also, look up "template metaprogramming."
I have a book called Game Programming Gems 5 I think which explains how you can create and destroy objects by referring to their names
Hi

Can you explain how they do it - I know one way you could do it is by doing the following(inherit a base class everytime ) and use a function which goes something like the following

Obj *GetClass(const std::string &className){   if(className.compare(someName))   {      return new ClassName();   }   return NULL;}


The more applications I write, more I find out how less I know
Quote:Original post by CRACK123
Hi

Can you explain how they do it - I know one way you could do it is by doing the following(inherit a base class everytime ) and use a function which goes something like the following

*** Source Snippet Removed ***
That function returns an instance (=object), not the class itself. Thus it should be named differently.

This topic is closed to new replies.

Advertisement