With a class and a derivative as shown below, is there a way for the base classes methods to return a object reference of the derived type instead of its own type so syntactically i can chain the methods together?
Suppose that object A
has methods a1,a2
and derivative AD
adds a method ad1
how would one go about making a valid method chain of AD_instance.a1().a2().ad1();
?
Below are the two classes in question. Ignoring what it's actually doing, the method chaining is the only important part.
class AsyncWorker() {
pthread_t worker;
public:
AsyncWorker();
void *worker_run();
AsyncWorker& Detach() { /*code*/ return *this; }
AsyncWorker& Start() {
pthread_create(&worker, NULL, &AsyncWorker::worker_helper, this);
return *this;
}
static void *worker_helper(void *context) {
return ((AsyncWorker *)context)->worker_run();
}
};
class workerA : public AsyncWorker {
public:
int a;
workerA(int i) { a = i; }
void* worker_run() { ++a; sleep(1); }
workerA& other_method_i_want_to_chain() { return *this };
};
Chained like so.
workerA A(0);
A.Start().Detach().other_method_i_want_to_chain();
You could create a suitable overload in your derived class which dispatches to the base class version but return an object of itself: