G
G
gense2019-11-01 00:56:01
Qt
gense, 2019-11-01 00:56:01

Is it possible to somehow pass the class by which the object will need to be created to the function parameter?

There is some function creator(...) which should create an object. But inside it it is not known what class it will be an object, it is known only when this function is called, "outside". Is it possible to somehow pass there a link or a class name by which this object will be created?
ZY I know that it is possible to create an object in the parameters creator (new MyClass) but in the same function the need to create this object is generally solved. You can create it every time, and then delete it if the creation was unnecessary, but this is a dirty hack and somehow not
humanly ZZY you can still take the logic of the decision to create an object or not to take it out of a function, but then I will violate the DRY principle. There, for each class, you will have to check

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vanyamba-electronics, 2019-11-01
@gense

template <class T>
T* create_class(T* object = nullptr)
{
   if (obj == nullptr) {
       obj = new T();
       if (obj == nullptr)
          throw Exception("Can't create " + std::string(name_of<T>()) + " object"); 
   }
   obj->init();
   return obj;
}
...
MyClass* mc = create_class<MyClass>();
delete mc;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question