noesbud
noesbud

Reputation: 11

How to pass a member function to a class constructor?

I want to pass my class Worker a pointer to a funtion, but something is wrong when im calling the constructor...

Worker.h

class Worker : public QObject
{
Q_OBJECT

public:
Worker(void (*process)());

public slots:
void work();

signals:
void error(QString error);
void paused();

private:
void (*_task)();
};

Worker.cpp:

Worker::Worker(void (*task)())
{
_task = task;
}

void Worker::work()
{
_task();
paused();
}

This is what i want to do... Worker should perform a function call of any function. (Update is a void without attributes, not static or const etc.)

Main.cpp:

_worker = new Worker(someClass->Update());

Upvotes: 0

Views: 568

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148870

Just a variant of Félicie's answer.

If you want to be able to pass methods operating on arbitrary objects, the C++11 way will be to use std::function and std::bind.

If for any reason you must use a pre C++11 system, you will have to revert to the C-ish style of passing arbitrary arguments, the good old void * type:

void someClassUpdateWrapper(void *obj) {
    SomeClassType someClass = static_cast<SomeClassType *>(obj);
    someClass->Update();
}

You will have to slightly change your declarations:

class Worker : public QObject
{
Q_OBJECT

public:
Worker(void (*process)(), void *obj);

...

private:
void (*_task)();
void *_obj;
};

then:

Worker::Worker(void (*task)(), void *obj;)
{
_task = task;
_obj = obj;
}

void Worker::work()
{
_task(_obj);
paused();
}

and finaly:

_worker = new Worker(someClassUpdateWrapper, static_cast<void *>(someClass));

But this looses all the possible type controls allowed by the C++11 way - the reason why std::function and std::bind were invented...

Upvotes: 0

Godineau F&#233;licie
Godineau F&#233;licie

Reputation: 438

First, when a function is a non static member function of a class, its first argument is the object from which its called.

In your example, the real code for your function Update() from the object someClass is "void Update(&someClass)"

Secondly, when you do Update(), you call the function and so, takes its return in your Worker constructor.

To use member function pointers, the syntax is : &ClassType::FunctionName

To use 'normal' function pointers, the syntax is : &FunctionName

In your exemple, you can for exemple turn Update function to static and change your constructor like this :

_worker = new Worker(&someClassType::Update);

Like someone said in the comments, if you want to improve your code, learn about std::function from C++11

Upvotes: 4

Related Questions