Can I handle class as objects in C++
c++, class
Solution
Are you looking for something like this?
template<typename T>
std::unique_ptr<base> make()
{
return std::unique_ptr<base>(new T);
}
class factory
{
static constexpr std::unique_ptr<Base> (*fns[])(){make<derived_a>, make<derived_b>};
std::unique_ptr<base> get_object_of_class(int const i)
{
if (i < 0 || sizeof fns / sizeof *fns <= i) {
return nullptr;
}
return fns[i]();
}
};
Problem
Here is what I am trying to achieve: I have a list of Classes (Class1 to Classn) which inherit from a main Class I would like to be able to instanciate an object of any of the n classes without having to do a large switch case (or equivalent). something along the lines of: ``` static ClassPointerType const * const ArrayOfClassTypes[]={ Class1, Class2, .. Classn }; static Class *GetObjectOfClass(int i) { return new ArrayOfClassTypes[i](some parameters for the constructor); } ``` You can do that in other OO langues like Delphi where you have a TClass type and can get the class of an object... but I was not able to locate the equivalent functionality in C++.