Skip to content

Instantiate a class

Julien SOYSOUVANH edited this page Apr 14, 2022 · 2 revisions

The Refureku API offers a way to instantiate structs and classes from their associated rfk::Struct object. This allows to instantiate a class without having access to its static type.

//ExampleClass inherits from ExampleClassBase

rfk::Class const* c = rfk::getDatabase().getFileLevelClassByName("ExampleClass");

rfk::SharedPtr<ExampleClassBase> instance = c->makeSharedInstance<ExampleClassBase>();
//or rfk::UniquePtr<ExampleClassBase> instance = c->makeUniqueInstance<ExampleClassBase>();

In this above example, instance is a pointer to an ExampleClass. This is especially useful to serialize/unserialize dynamically allocated objects:

//WARNING: This is only an example, serialize, unserialize or SerializedData are NOT part of the Refureku API

rfk::SharedPtr<ExampleClass> instance = rfk::makeSharedInstance<ExampleInstance>();

//Save
SerializedData data;

data.write(instance->getId());  //Write class Id
instance->serialize(data);      //Save ExampleClass to data
data.save("SavedFile");

//Later (in a potentially subsequent program execution)
SerializedData loadedData("SavedFile");

std::size_t classId = loadedData.read<std::size_t>();
rfk::Class const* c = rfk::getDatabase().getClassById(classId);

//We don't know the concrete type of the class but we know it inherits from ExampleInstanceBase
rfk::SharedPtr<ExampleClassBase> instance = c->makeSharedInstance<ExampleInstanceBase>();
c->unserialize(loadedData); //Restore ExampleClass state

See the Instantiator property to see how to add instantiators to a class.

Clone this wiki locally