J
johnmmcparland
Hi all,
when I write a subclass, can I inherit its superclass' << operator?
As an example say we have two classes, Person and Employee.
class Person has the << operator;
Now in class Employee I want this same behaviour plus some extra
behaviour for the fields which Employee has and Person doesn't;
I would have thought that since Person:perator() returns an ostream&
that assigning it to the existing o would be ok. However it isn't as
this compiler message informs me;
Now I understand this since it is not a member function as it is
declared as follows;
in person.hpp.
So how do I get round this problem? Basically I want to take the
returned ostream& from class Person's operator<< method and insert it
into the ostream& object in class Employee's operator<< method.
Thank,
John
when I write a subclass, can I inherit its superclass' << operator?
As an example say we have two classes, Person and Employee.
class Person has the << operator;
Code:
/**
* Insertion operator
* @param o The output stream to insert a person into
* @param p The person to insert into a stream
*/
ostream& operator<<(ostream& o, Person& p)
{
o << p.m_surname << ", " << p.m_firstname;
if (p.m_middlename != "")
o << p.m_middlename;
o << " (" << p.m_dob << ") " << "[";
if (p.m_gender == Person::male)
o << "M";
else if (p.m_gender == Person::female)
o << "F";
else // Shouldn't happen
o << " ";
o << "]";
return o;
}
Now in class Employee I want this same behaviour plus some extra
behaviour for the fields which Employee has and Person doesn't;
Code:
/**
* Output to a stream
*
* @param o The output stream to write to
* @param emp The employee to write to an output stream
*/
ostream& operator<<(ostream& o, Employee& emp)
{
o= Person::operator<<(o,emp);
o << std::endl << "Started: " << emp.m_startDate
<< " Role: " << emp.m_job << "Dept: " << emp.m_department
<< std:: endl; << "Salary: " << emp.m_salary << std::endl;
return o;
}
I would have thought that since Person:perator() returns an ostream&
that assigning it to the existing o would be ok. However it isn't as
this compiler message informs me;
Code:
operator<< is not a member of Person
Now I understand this since it is not a member function as it is
declared as follows;
Code:
friend ostream& operator<<(ostream& o, Person& p);
in person.hpp.
So how do I get round this problem? Basically I want to take the
returned ostream& from class Person's operator<< method and insert it
into the ostream& object in class Employee's operator<< method.
Thank,
John