How to pass a function pointer that points to constructor?

Lambda style:

[](){return new YourClass();}

I encountered this same problem. My solution was a template function which called the constructor.

template<class T> MyClass* create()
{
    return new T;
}

To use this as a function pointer is simple:

MyClass* (*createMyClass)(void) = create<MyClass>;

And to get an instance of MyClass:

MyClass* myClass = createMyClass();

You cannot take the address of a constructor (C++98 Standard 12.1/12 Constructors - "12.1-12 Constructors - "The address of a constructor shall not be taken.")

Your best bet is to have a factory function/method that creates the Object and pass the address of the factory:

class Object;

class Class{
public:
   Class(const std::string &n, Object *(*c)()) : name(n), create(c) {};
protected:
   std::string name;     // Name for subclass
   Object *(*create)();  // Pointer to creation function for subclass
};

class Object {};

Object* ObjectFactory()
{
    return new Object;
}



int main(int argc, char**argv)
{
    Class foo( "myFoo", ObjectFactory);

    return 0;
}