Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I pass a function as a parameter in c++

class Stepper
{
public:
  Stepper(int en,int dir, int clk, void(*f))
  {

  }
};
class Turret : public Stepper
{
public:
  Turret(int x,int y, int z,void (*f)):Stepper(x,y,z,void(*f))
  {
  }
};
void TurretStep()
{

}
Turret t(2,3,4,TurretStep);

Alright so this gives me a void* is not a pointer-to-object type. All i'm trying to do is pass a void function as a parameter to my constructors.

like image 663
Dalton Moore Avatar asked Feb 07 '23 16:02

Dalton Moore


2 Answers

You have 2 problems.

The first is you don't have the correct syntax for a function pointer.

The syntax for a function pointer is

return_type(*name)(arguments)

Since your function has void return type and doesn't take any arguments, it's

void(*f)()

The second is in trying to pass the function pointer f to the base class constructor

Here you're passing the type to the base class, when in fact you just want to pass the variable

Incorrect (both in terms of the syntax and passing the type of the argument)

Stepper(x,y,z,void(*f)) 

Correct (just pass f, the function pointer variable itself

Stepper(x,y,z,f)

Here is the code with the fixes:

class Stepper
{
public:
  Stepper(int en,int dir, int clk, void(*f)())
  {

  }
};
class Turret : public Stepper
{
public:
  Turret(int x,int y, int z,void (*f)()):Stepper(x,y,z,f)
  {
  }
};
void TurretStep()
{

}
Turret t(2,3,4,TurretStep);
like image 152
Steve Lorimer Avatar answered Feb 15 '23 10:02

Steve Lorimer


You forgot to add the empty parenthesis to the function pointer:

void(*f)()
        ^^
     no arguments

Also, Stepper(x,y,z,void(*f)) is also wrong, because f is just a variable (like x, y and z), so why cast it to void?

Stepper(x, y, z, f); //'f' is just like a "normal" variable
like image 32
Rakete1111 Avatar answered Feb 15 '23 10:02

Rakete1111