Ravi
Ravi

Reputation: 21

C++; How to turn a string (name of class) into a type?

A function should take in the name of a class and return an object of that type. How to do it in C++?

Upvotes: 2

Views: 214

Answers (3)

Depending on the exact requirements of your problem you might be asking about reflection (in the most general case) which is not natively supported by the language, but for which you might find some libraries, or a form of the factory pattern, where you create a function that receives a set of parameters and returns an object of the appropriate type. The second case is a much more limited scenario, where the types must be related, and you have to implement the factory...

So the question, would be, can you extend on your particular requirements?

Upvotes: 2

Sebastian Mach
Sebastian Mach

Reputation: 39089

You would have to rely on frameworks that introduce reflection on your objects, like the Qt Meta Object System, or write your own.

However, this is not true reflection and only works with your manual help, either in form of the need to invoke tools, or in form of you having to register the instantiable classes to the framework.

Upvotes: 0

Andreas Brinck
Andreas Brinck

Reputation: 52519

That's called reflection and is not part of the C++ language. It's possible to implement with something usually called a factory pattern. The way it works is that for each type you want to be able to create you create a mapping between a function that can create an object of this type and it's name.

This mapping could be something as simple as a std::map where the key is the name of the class and the value is a function pointer to a function returning a new instance of the class.

Upvotes: 7

Related Questions