-
overloading << problems
Hi,
I am trying to overload << as a friend class. As far as I understand, if class "a" declares "friend class b" then class b should be able to access all private and public members of class a, if this is incorrect then I have more problems than I thought. Otherwise, why doesn't this code work? The compiler error is :
error C2248: 'emp_name' : cannot access private member declared in class 'employee'
This is the relevant segment of the code:
Code:
class employee
{
private:
char *emp_name;
double rate, current_charge;
int current_job_hrs;
public:
employee(double e_rt, char *e_nam="Able", int e_curr_hrs=0)
: rate(e_rt), current_job_hrs(e_curr_hrs)
{
strcpy(emp_name, e_nam);
}
~employee()
{
cout << "Consultant destructor called for "
<< *emp_name
<< " by Matt Rossner and Vic Uppal"
<< endl
<< endl;
delete emp_name;
}
void set_current_job_hrs(int hrs) { current_job_hrs = hrs; }
virtual void calc_charge() { current_charge = current_job_hrs * rate; }
friend ostream& operator <<(ostream& out, const employee& emp);
};
class home_employee : public employee
{
private:
double office_rate;
public:
home_employee(char *he_name, double he_rt, double he_ofc_rt=5);
friend ostream& operator <<(ostream& out, const employee& emp)
{
out << "For home employee named "
<< emp.emp_name
<< "the charges so far are $"
<< emp.current_charge;
return out;
}
};
home_employee::home_employee(char *he_name, double he_rt, double he_ofc_rt)
: employee(he_rt, he_name), office_rate(he_ofc_rt) {}
ostream& operator <<(ostream& out, const home_employee& emp)
{
out << "For employee named "
<< emp.emp_name
<< "the charges so far are $"
<< emp.current_charge;
return out;
}
Thanks for any help out there.
-
Looks like you are confusing a few things. Don't confuse the difference between a friend function and a friend object.
All of the "operator <<()" functions are just that, functions - ie. not methods of any class. The compiler knows what to call by type matching on the functions parameters.
This function is not declared as a friend of any object
Code:
ostream& operator <<(ostream& out, const home_employee& emp)
If you want this function to access non-public members of home_employee, then the function must be declared a friend in that class.
If you want to use polymorphism for printing, then add something like this to your base class, then you only need to overload operator<<() once for the base class by simply calling print()
Code:
virtual ostream& print(ostream &out) const;
gg
-
Member or friend functions of a derived class do not have a direct access to private data of base class.
-
thanks alot, I will make some modifications