Is there any way to add a field to a class at runtime ( a field that didn’t exist before ) ? Something like this snippet :
Myobject *ob; // create an object ob->addField('newField',44); // we add the field to the class and we assign an initial value to it printf('%d',ob->newField); // now we can access that field
I don’t really care how it would be done , I don’t care if it’s an ugly hack or not , I would like to know if it could be done , and a small example , if possible .
Another Example: say I have an XML file describing this class :
<class name='MyClass'> <member name='field1' /> <member name='field2' /> </class>
and I want to ‘add’ the fields ‘field1’ and ‘field2’ to the class (assuming the class already exists) . Let’s say this is the code for the class :
class MyClass { };
I don’t want to create a class at runtime , I just want to add members/fields to an existing one .
Thank you !
Use a map and a variant.
For example, using boost::variant. See http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html
(But of course, you can create your own, to suit the types of your XML attributes.)
By adding MyValueMap as a member of your class, you can add properties according to their names. Which means the code:
By encapsulating it in a MyObject class, and adding the right overloaded accessors in this MyObject class, the code above becomes somewhat clearer:
But you lose somewhat the type safety of C++ doing so. But for XML, this is unavoidable, I guess.