Approach 1:
class Employee
{
public:
virtual int calculateSalary() = 0;
};
class PermanentEmployee : public Employee {
const int salaryPerMonth;
public:
PermanentEmployee(int sal) : salaryPerMonth(sal){}
int calculateSalary() {
return salaryPerMonth;
}
};
class ContractEmployee : public Employee {
const int wagesPerHr;
int totalHour;
public:
ContractEmployee(int sal) : wagesPerHr(sal), totalHour(0){}
void setWorkingDuration(int time) {
totalHour = totalHour + time;
}
int calculateSalary() {
return wagesPerHr * totalHour;
}
};
class Manager {
list<Employee *> ls;
public:
void assignWorkingHour() {
list<Employee *>::iterator it;
for(it = ls.begin(); it != ls.end(); it++) {
Employee *emp = *it;
ContractEmployee* contractEmp = dynamic_cast<ContractEmployee* >(emp);
if(contractEmp) {
contractEmp->setWorkingDuration(5);
}
}
}
};
In problem, there are 2 type of Employee
: PermanentEmployee
and ContractEmployee
.
There is a class called Manager
which contains a list of all employee working under him.
For ContractEmployee
, it has to invoke function setWorkingDuration()
, which is being invoked in method assignWorkingHour
of class Manager
.
The problem is:
Here type of Employee
is being determind by dynamic_cast
operator and Manager
has to know about all type of derive class of Employee
.
Approach 2:
Add another member in class Employee
:
enum TypeOfEmployee {CONTRACT, PERMANENT};
and check TypeOfEmployee
to determine the type of Employee
Please tell me which is better or is there any alternative approach?