0

In C# an object can be created based on knowledge of the desired type like this (among a few other ways)

public T GetInstance<T>(string type)
{
    return (T)Activator.CreateInstance(Type.GetType(type));
}

Is there an equivalent way of doing this in native c++?

I have a base class and a derived class. I wish to construct the proper object based on stored data. I have control over what this stored data is, but I need to know what information needs to be stored to identify the type and then how to use that data to later call a constructor.

I'm essentially looking for the c++ answer to this question: Dynamically create an object of <Type>

Community
  • 1
  • 1
Russell Trahan
  • 783
  • 4
  • 34
  • 1
    reflection is not possible in C++. But if you know what data you have stored, you can use polymorphism – Creris Nov 20 '14 at 18:38
  • I know reflection doesn't exist. I'm just using the c# example to outline the goal that I have. I'm sure the solution involves typical c++ classes and inheritance but I'm a bit lost at the moment on how to accomplish this. – Russell Trahan Nov 20 '14 at 18:39
  • `base* b = nullptr; if (DATA == SOME_DATA) { b = new base(); } else if (DATA == SOME_OTHER_DATA) { b = new derived(); } /* work with b, or return it*/` – Creris Nov 20 '14 at 18:41
  • I don't wish to hard-code the possible derived types. – Russell Trahan Nov 20 '14 at 18:43
  • `template base* createBase(T&& dummy, Args...&& args) { return new T(args...); }`. Sorry if the variadic template has incorrect syntax, I only worked with it once or twice. – Creris Nov 20 '14 at 18:45
  • You are looking for the [factory](http://en.wikipedia.org/wiki/Factory_%28object-oriented_programming%29) concept. – n. m. could be an AI Nov 20 '14 at 18:45
  • Does `Activator.CreateInstance` not `hard-code the possible derived types` ? –  Nov 20 '14 at 18:50
  • `Activator.CreateInstance` is part of .Net Framework so no it does not hardcode since it is able to instantiate custom types. – Russell Trahan Nov 20 '14 at 18:51

0 Answers0