@
@
@broken2013-12-13 11:50:23
C++ / C#
@broken, 2013-12-13 11:50:23

Is it possible to create an object at runtime in C++?

Help people.
I kind of know what introspection is, using C# and Python as an example. In the latter, a complex object is dynamically created in my project at runtime. Is it possible to create an object in C++ at runtime (and access it in advance from the code)?
For example, something like this:
auto object = ObjectFactory::genererateObject(objectToParse);
object.field1.field2 = NULL;
In the spirit of this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nicolausYes, 2013-12-13
_

The question is a little unclear. But as you wrote, yes, you can. During compilation, the compiler will determine the type that your class returns and substitute it for "auto". If you access invalid fields that are not native to that type, the compiler will tell you this at compile time.
But still the example you gave is not introspection. Introspection in C++ is achieved through RTTI. In your example, the type of the object is known at compile time.

T
tsarevfs, 2013-12-13
@tsarevfs

you can try something like this:

typedef boost::variant<int, string, bool> field_t;
typedef std::map<string, field> settings_t;
struct A
{
   A(file)
   : settings_(file.parse())
   {}
private:
   settings_t settings_;
   int my_method()
   {
      int a = boost::get<int>(settings_["a"]);
      int b = boost::get<int>(settings_["b"]);
      return a + b;
   }
}

M
Mercury13, 2013-12-17
@Mercury13

Let me put in my 5e−2 P ...
Is there anything known about what type our auto will be? If you know, it might just work.
dynamic_cast<Type>(object).field1.field2 = NULL;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question