Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function pointer that points to constructor?

I'm working on implementing a reflection mechanism in C++. All objects within my code are a subclass of Object(my own generic type) that contain a static member datum of type Class.

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

For any subclass of Object with a static Class member datum, I want to be able to initialize 'create' with a pointer to the constructor of that subclass.

like image 767
Kareem Avatar asked Jun 05 '09 06:06

Kareem


People also ask

Can we have a pointer to a constructor?

Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the {body} and even in the initialization list) if you are careful.

Can we pass pointer to copy constructor?

You can write any constructor you want, and it can take a pointer if you want it to, but it won't be a "copy constructor".

Can we call member function using this pointer in constructor?

the constructor is the first function which get called. and we can access the this pointer via constructor for the first time. if we are able to get the this pointer before constructor call (may be via malloc which will not call constructor at all), we can call member function even before constructor call.


1 Answers

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; } 
like image 166
Michael Burr Avatar answered Sep 24 '22 10:09

Michael Burr