How is an instance initializer different from a constructor?

This seems to explain it well: Instance initializers are a useful alternative to instance variable initializers whenever: initializer code must catch exceptions, or perform fancy calculations that can’t be expressed with an instance variable initializer. You could, of course, always write such code in constructors. But in a class that had multiple constructors, you would … Read more

Creating an instance using the class name and calling constructor

Yes, something like: Class<?> clazz = Class.forName(className); Constructor<?> ctor = clazz.getConstructor(String.class); Object object = ctor.newInstance(new Object[] { ctorArgument }); That will only work for a single string parameter of course, but you can modify it pretty easily. Note that the class name has to be a fully-qualified one, i.e. including the namespace. For nested classes, … Read more

What exactly is “broken” with Microsoft Visual C++’s two-phase template instantiation?

I’ll just copy an example from my “notebook” int foo(void*); template<typename T> struct S { S() { int i = foo(0); } // A standard-compliant compiler is supposed to // resolve the ‘foo(0)’ call here (i.e. early) and // bind it to ‘foo(void*)’ }; void foo(int); int main() { S<int> s; // VS2005 will resolve … Read more

What is the difference between “Class.forName()” and “Class.forName().newInstance()”?

Maybe an example demonstrating how both methods are used will help you to understand things better. So, consider the following class: package test; public class Demo { public Demo() { System.out.println(“Hi!”); } public static void main(String[] args) throws Exception { Class clazz = Class.forName(“test.Demo”); Demo demo = (Demo) clazz.newInstance(); } } As explained in its … Read more

Is there a way to instantiate objects from a string holding their class name?

Nope, there is none, unless you do the mapping yourself. C++ has no mechanism to create objects whose types are determined at runtime. You can use a map to do that mapping yourself, though: template<typename T> Base * createInstance() { return new T; } typedef std::map<std::string, Base*(*)()> map_type; map_type map; map[“DerivedA”] = &createInstance<DerivedA>; map[“DerivedB”] = … Read more