2

I have this code:

#ifndef FUNCSTARTER_H
#define FUNCSTARTER_H

#endif // FUNCSTARTER_H

#include <QObject>

class FunctionStarter : public QObject
{
    Q_OBJECT
public:
    FunctionStarter() {}
    virtual ~FunctionStarter() {}

public slots:
    void FuncStart(start) {
        Start the function
    }
};

In the FuncStart function, you would put your function in as a parameter and then it would execute the parameter (aka the function). How would I do this?

2 Answers 2

3

either you pass a function pointer, or you define a functor class. A functor class is a class that overloads operator(). This way, the class instance becomes callable as a function.

#include <iostream>

using namespace std;

class Functor {
public:
    void operator()(void) {
        cout << "functor called" << endl;
    }   
};


class Executor {
    public:
    void execute(Functor functor) {
        functor();
    };  
};


int main() {
    Functor f;
    Executor e;

    e.execute(f);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You'd pass the function pointer as parameter. This is called a callback.

typedef void(*FunPtr)();  //provide a friendly name for the type

class FunctionStarter : public QObject
{
public:
    void FuncStart(FunPtr) { //takes a function pointer as parameter
        FunPtr();  //invoke the function
    }
};

void foo();

int main()
{
    FunctionStarter fs;
    fs.FuncStart(&foo); //pass the pointer to the function as parameter
                        //in C++, the & is optional, put here for clarity
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.