Question

I'm trying to create an object from these classes and i get an error in the main() on this line:

employee1->employeeId(29);

The error just says that "employeeId is set to protected", however this should work. All help is appreciated thx :)

Here's my code below:

Code Deleted*

Was it helpful?

Solution

Well the compiler is correct, employeeId is protected. Are you sure you didn't mean to use setEmployeeId instead?

e.g.

employee1->setEmployeeId(29);

OTHER TIPS

Yes, it is protected, so you cannot access it from main only from methods of derived classes. And you cannot use it as a function: employee1->employeeId(29); it is a member variable of type int.

Protected means that only the derivative (child) classes can see that member. Users of the derivative classes cannot see it just as users of the parent class could not see it. The use of "public" in the inheritance does not change the protection of all of the members, but controls the protection of the parent from users and/or children of the child.

Here's another thread with related information: Difference between private, public, and protected inheritance

As a general rule of thumb here, you shouldn't be using a set method to simply return data -- stylistically speaking, this should be getId(); your setters should actually set data. But then again, it looks like you already have a setter in your parent, so add a getter and remove everything from your child.

Your class could be cleaned up a bit just by following this style.

class Employees{
    protected:      
        int employeeId; 
        //string name;
    public:         
        void setEmployeeId(int a)
        { employeeId = a; }    
        int getEmployeeId()
        { return employeeId; }    
};

class cashier: public Employees{
    public:
    // no need for anything here -- the methods you need are inherited  
};

int main(){
    cashier c;      
    c.setEmployeeId(29);
    cout << "Employee ID: " << c.getEmployeeId() << endl;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top