How do you accepts a Worker(class) object and assigns it to the supervisors(class) array, if the supervisors array is not defined in the supervisors class
This is what i have, im pretty sure its not doing as stated acove
Why would you not use std::vector? It is a useful and carefully designed container.
Your Supervisor::addSubordinate() has "issues". It dynamically allocates memory (from heap) for four Employee objects and stores the location in a pointer "array". As already stated, the line is legal only if Employee IS-A Supervisor.
However, line 5 attempts to reset the "array". The new value of "array" would not be a memory address, but a value from memory address, where the pointer "ptr" points to. Such assignment is not possible, and even if it were, no-one would remember any more where the memory block of four default-constructed Employees is in the heap.
When you exit from the function, the scope of local variable "array" ends, and no-one will remember any more where the memory block of four default-constructed Employees is in the heap.
You did ask, "how to assign to a variable that does not exist?" You simply can not. You have to give a broader view to your actual problem, before anyone can help.
If we want to do it without dynamic memory allocation, we can. If we want to avoid std::vector and stick with arrays, we can. However, we need some rules. For example:
- A supervisor may have no more than 8 employees.
We can easily link a supervisor to an employee because an employee only has one supervisor:
1 2 3 4 5 6 7 8 9 10 11
class Supervisor;
class Employee
{
Supervisor* supervisor;
public:
void LinkSupervisor(Supervisor* sup);
{
supervisor = sup;
}
};
Linking an employee to a supervisor is a little more difficult
1 2 3 4 5 6 7 8 9 10 11 12
class Employee;
class Supervisor
{
Employee* employees[8]; // remember we are limited to 8.
int nb_minions; // The number of underlings... Constructor must set this to 0
public:
void LinkEmployee(Employee* emp)
{
employees[ nb_minions++ ] = emp;
}
};
If we really want to simplify our interface and make this very easy for the executive class, then we could say that when we assign a supervisor to that employee, the Supervisor is responsible for linking the employee to himself.
1 2 3 4 5 6 7 8 9 10 11 12
class Supervisor
{
Employee* employees[8]; // remember we are limited to 8.
int nb_minions; // The number of underlings... Constructor must set this to 0
public:
void LinkEmployee(Employee* emp)
{
employees[ nb_minions++ ] = emp;
emp->LinkSupervisor(this); // Now the employee is linked to this supervisor.
}
};
Absolutely. Actually, I had the nb_minions <= 8 check in there but took it out to avoid complicating it for OP. The Unlink method is significantly more complicated than the Link method, but I'm sure OP will discover that soon and will understand why std::vector is the preferred container.