-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflection.cpp
38 lines (29 loc) · 855 Bytes
/
reflection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
#include<string>
#include<map>
class Reflectable {
public:
virtual std::string getClassName() const = 0;
virtual Reflectable* createInstance() const = 0;
};
class MyClass : public Reflectable {
public:
std::string getClassName() const override {
return "MyClass";
}
Reflectable* createInstance() const override {
return new MyClass();
}
};
int main() {
std::map<std::string, Reflectable*> classRegistry;
// Register MyClass
MyClass myInstance;
classRegistry["MyClass"] = &myInstance;
// Create an instance dynamically based on the class name
Reflectable* newInstance = classRegistry["MyClass"]->createInstance();
// Do something with the new instance...
// Don't forget to delete the dynamically allocated instance
delete newInstance;
return 0;
}