0

Is it possible to perform reflection in c++, and instantiate a class given the name of it as a string?

Cheers,

Nick
  • 1,269
  • 5
  • 31
  • 45
  • 1
    There's no reflection in C++. Your best bet is to map a string to the class it represents. – David G Nov 25 '13 at 23:50
  • In general no, of course you can write code of the form `if (className == "XYZ") p = new XYZ(); else if (className == "ABC") p = new ABC();` etc – john Nov 25 '13 at 23:50
  • 1
    No and no. But this sounds like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Maybe if you described what you're trying to achieve, someone can suggest an alternate solution. – Praetorian Nov 25 '13 at 23:51
  • Note a duplicate, but quite-related and a helluva read: [Why does C++ not have reflection?](http://stackoverflow.com/questions/359237/why-does-c-not-have-reflection) – WhozCraig Nov 25 '13 at 23:51

2 Answers2

5

There's no language feature that lets you do this. You can, however, write your own set of factory functions and put those in a string-indexed map.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

If you can use MFC, it has a object serialization framework that allows you to do this. This is documented here. Just to clarify, MFC can be used for a UI less application and I have seen it being used in this way quite successfully.

If you can't use MFC, you can consider boost serialization library. But to my knowledge it does not provide a factory function that allows you to create classes given their names. However, it does have the mechanisms to dynamically create classes from their names which you may be able to adapt to your unique needs. The relevant doc is here.

Hari Mahadevan
  • 920
  • 7
  • 14