Home > Software design >  Execute function within the constructor call
Execute function within the constructor call

Time:10-19

What I would like to achieve is the following: I want to allow the users to only create objects of class A if they provide a function - this function may construct and calculate things and set other members of the object. In short, I need a way to only allow a constructor call that includes a function as an argument that is subsequently executed with said constructor call. Imagining it like filling those blanks right now:

void foo()
{
// do something
}


class A
{
public:
    A(/*magic*/);

/*
...
*/


A:A()
{
    /*magic*/
}

I have read about function pointers but have yet to figure out what this syntax:

int (*const fcnPtr)();

translates into and how I can achieve what I want to achieve with it - assuming this is the "best" way in the first place.

Whatever closes the chain of function definition -> constructor call with link to function -> executing the function during object construction is of interest to me.

Thank you for reading and thank you in advance for any input.

CodePudding user response:

The easiest way to do it is by a template:

class A
{
public:
    int i;

    template<typename F>
    A(F f)
    : i(0) /* and other initializers*/
    { f(); } // no need to pass *this, see below
};

// usage:
A a([&]() { a.i = 0; });

CodePudding user response:

Looking at your given example, you can add a function pointer as parameter of the constructor:

void foo()
{
  std::cout <<" foo called" << std::endl;
}
void bar()
{
    std::cout << "bar called" << std::endl;
}


class A
{
public:
//-----------vvv------->ptr is a pointer to a function that has no parameter and return type void 
    A(void (*ptr)());

};


A::A(void (*ptr)())
{
    //call through ptr 
    ptr(); 
}
int main()
{
    A a(foo); //this will call foo 
    
    A b(bar); //this will cal bar
}
  • Related