Inheritance and "private within context"

Hi again.
I am struggling with one thing right now. I wanna make 2 classes - worker and employee in this way :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Worker 
{
    public :
        Position p;
        double salary;
        ...
    private :
        ....
};

class Employee : public Worker
{
    public : 
        ...
    private : 
        ...
};

With 'position' being an enum type of "worker, employee, main boss etc". In a constructor of "Employee" I want it to change the 'position' to employee but it says it cannot access it as its a private thing. Is there a way to do it? Of course I dont wanna make a public method in the Worker class to do things like that cause of safety issues (to avoid giving workers an employee status etc).

Edit:
of course I made a typo, "p" and salary are private not public, with the constructor etc being public.
Last edited on
If you're using Worker.p to identify the type of the worker, what's the point in the inheritance hierarchy? Either you're using dynamic polymorphism and virtual functions do what's right at runtime, or you're using static polymorphism and deriving from Worker<Employee>.

That said, there is no reason why what you described would give the error you described:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Worker
{
    public :
        enum Position { EMPLOYEE, BOSS };
        Worker(Position p) : p(p) {}
    private :
        Position p;
        double salary;
};

class Employee : public Worker
{
    public :
        Employee() : Worker(EMPLOYEE) {}
    private :
};

int main()
{
    Employee e;
}
demo: http://ideone.com/iO9Wy
Last edited on
Is your constructor for Worker declared public or private?
If it's private, Employee won't be able to access it.

Since you're concerned about safety, Position and salary should be protected or private, not public.

Your code should look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Worker 
{
    private:  // implicit here, but stated for clarity
        Position p;
        double salary;
        ...
    public:
        Worker (Position pos, double sal) 
        { p = pos; salary = sal; }   // Initialize Worker's private members
};

class Employee : public Worker
{
    public : 
        Employee (Position pos, double sal);
        ...
    private : 
        ...
}; 

...
// Create an employee
Employee * emp;
emp = new Employee(worker, 10.00);

Topic archived. No new replies allowed.