I am developing a code using Boss-Worker model pattern. I have a doubt.
The list which the Boss will be adding to, is a member of the Boss class.
In order for the Worker to access it, I am making the Worker class inherit from Boss.
1) Is this the right way to share the list between the Boss & Worker?
2) I am facing ambiguous inheritance in my code. How can I solve it?
ThreadClass
#include <pthread.h>
class ThreadClass
{
public:
virtual int start();
virtual void join();
virtual void execute() = 0; //Each derived class will implement this
virtual ~ThreadClass() {}
ThreadClass() {}
private:
ThreadClass* Tptr;
};
Boss
#include "ThreadClass.h"
#include <list>
class Boss : public virtual ThreadClass
{
public:
virtual void execute();
Boss() {}
~Boss() {}
protected:
std::list<int> Mylist; //To be shared with the worker
};
Worker
#include "ThreadClass.h"
#include "Boss.h"
class Worker : public Boss, public ThreadClass //Getting error:Ambiguous ThreadClass
{
public:
virtual void execute();
Worker() {}
~Worker() {}
};
Worker is inheriting from Boss & ThreadClass because:
1) Worker needs access to the list from Boss
2) Worker needs threading functions from ThreadClass
This is categorically not a good reason for one class to inherit from another. Usually,
Workershould inherit fromBossif and only if you can substitute aWorkerin any place that you could use aBoss. Conceptually, this is not the case here.If you want to provide access to
Boss‘s list ofintthen, if theWorkerknows about theBossprovide and accessor for it inBossor (possibly) makeWorkerafriendofBoss.If you don’t want
Workerto know aboutBossbut instead haveBossknow aboutWorkers then makeBosspass the list to theWorkereither at construction time or at a suitable time later.Providing access to something is not a reason for making one class derive from another.