1

Possible Duplicate:
How to pass a function pointer that points to constructor?

Is it possible to pass to a function a function pointer to an object's constructor?

Something like

myFunction( myObj() );

and how should the function be declared in that case?

void myFunction( (*ObjConstructorPointer)() )

doesn't work because there's no return type

Community
  • 1
  • 1
Johnny Pauling
  • 12,701
  • 18
  • 65
  • 108
  • 1
    What would it mean if you could do that? What would be the result of calling the constructor? – jalf Oct 27 '12 at 16:40
  • What are you expecting to be able to do here? If `myObj` is an object of class type, its constructor has already been called when it was created. Why would you want a pointer to its constructor? `myObj()` would just call `operator()` on `myObj`. If `myObj` is a type, then `myObj()` is just creating a temporary object of that type. – Joseph Mansfield Oct 27 '12 at 16:49
  • If you want to call the constructor of an object, used placement `new`, which basically exactly calls the constructor with the `this` pointer set to whatever address you give it. The downside is that you have to use templates if you want to parameterise such a function, you can't do it at runtime. Or, you could pass function pointers that take a pointer and call placement `new` on that pointer if you want to do it at runtime, so you could do that at runtime, and create said functions with templates. – Seth Carnegie Oct 27 '12 at 16:51
  • The only reason I can think of is if you wanted to construct objects of a type that is *unknown* inside `myFunction`. If that is the case, and (for simplification) considering that you have a hierarchy, consider using the factory pattern – David Rodríguez - dribeas Oct 27 '12 at 16:53

0 Answers0