# Reflection in C++

In building simul I’ve found it necessary to implement reflection in C++. Reflection is where you can dynamically get information about a class, even use its functions and members, at runtime rather than compile time.

For instance, in the terminology of the SEAL library:

const Class* mc = Class::forName("MyClass");
const std::vector<const Method*> methods =  mc->methods();

etc. Now you can already get a string of the class name using the built-in real-time type info (RTTI) of C++, like this:

string type_name=typeid(object).name();

This will give you a fully-qualified, namespaced string like “struct plants::trees::Cedar”. What it won’t give you is pretty much anything else. You can check if two objects are of the same class – maybe useful if you only have base class pointers and want to know if they’re the same derived class. But not much else.
You can use dynamic_cast if RTTI is active – as long as the base class has a virtual function, dynamic_cast will work. But it’s actually a really slow function, not something you want to use in loops.

I was looking for a way to expand on this functionality without forcing anyone writing a new class to put a lot of boilerplate in their definitions. The solution I’m working with now is the export table. When you write a DLL, you declare the symbols you want to export like so:

class __declspec(dllexport) MyClass
{
...
}

This puts the class definition in the export table, either in the DLL itself or a separate exports file. Interestingly, you don’t have to be making a DLL to make an export table – at least in Visual Studio, the same declaration can make a table in a plain old executable. So this is our current reflection solution – declare all the classes we want reflected as dll exports, and read the exe’s table on startup. We get a big table of classes, member functions and so on. Then using typeid() we can get a class’s name and look it up in the table.