jyim
jyim

Reputation: 119

Mistake re: inheritance of private members?

Is this a mistake? I thought private members are not inherited from the base class:

"The definition of the class HourlyEmployee does not mention the member variables name, ssn, and netPay, but every object of the class HourlyEmployee has member variables namedname, ssn, and netPay. The member variables name, ssn, and netPay are inherited from the class Employee."

 //This is the header file hourlyemployee.h.
 //This is the interface for the class HourlyEmployee.
 #ifndef HOURLYEMPLOYEE_H
 #define HOURLYEMPLOYEE_H

 #include <string>
 #include "employee.h"
 using std::string;


namespace SavitchEmployees
{
class HourlyEmployee : public Employee
{
public:
    HourlyEmployee( );
    HourlyEmployee(const string& theName, const string& theSsn,
    double theWageRate, double theHours);
    void setRate(double newWageRate);
    double getRate( ) const;
    void setHours(double hoursWorked);
    double getHours( ) const;
    void printCheck( );
private:
    double wageRate;
    double hours;
};
 }//SavitchEmployees
 #endif //HOURLYEMPLOYEE_H

Other header file:

//This is the header file employee.h.
//This is the interface for the class Employee.
//This is primarily intended to be used as a base class to derive
//classes for different kinds of employees.
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>

using std::string;

namespace SavitchEmployees
{
    class Employee
    {
    public:
        Employee( );
        Employee(const string& theName, const string& theSsn);
        string getName( ) const;
        string getSsn( ) const;
        double getNetPay( ) const;
        void setName(const string& newName);
        void setSsn(const string& newSsn);
        void setNetPay(double newNetPay);
        void printCheck( ) const;
    private:
        string name;
        string ssn;
        double netPay;
    };
}//SavitchEmployees

#endif //EMPLOYEE_H

Upvotes: 0

Views: 141

Answers (4)

NPE
NPE

Reputation: 500237

The quote is correct. All data members, private or not, are inherited by the derived classes. This means that every instance of every derived class contains them. However, private members are not directly accessible by the derived classes.

You can, however, access such member though public or protected accessors, such as getName().

Upvotes: 2

geniaz1
geniaz1

Reputation: 1183

You have the Protected access level just for that. So use protected instead of private.

Upvotes: -1

melpomene
melpomene

Reputation: 85767

All members are inherited by subclasses. They just can't be accessed (directly) if they're private. They can still be accessed indirectly by calling public methods such as setName.

Upvotes: 3

cHao
cHao

Reputation: 86506

Private members exist in subclasses, but are not accessible in most cases. Only functions in the base class can touch them, absent a friend declaration or byte-level hackery.

Upvotes: 2

Related Questions