On Mar 22, 8:54 am, "johnmmcparland" <johnmmcparl...@googlemail.com>
wrote:
Quote:
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;
>
[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)
|
This operator is not a member. It's an overloaded operator<< that
takes a
Person& as its second argument. (Incidentally, the second parameter
should
probably be declared const.)
Quote:
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;}
|
And here you're not *overriding* the base class' operator<< (you can't
override a non-member). You're defining another overloaded operator<<
that
takes an Employee& as its second argument.
In the first statement above you're trying to call the operator<< for
person as if it were a member function. It should be written
operator<<(o, static_cast<Person&>(emp));
or simply,
o << static_cast<Person&>(emp);
Incidentally, you don't need or want to assign the return value of
operator<<
back to o. It doesn't do what you think. operator<< returns a
reference to the
left hand operand so that you can chain the operator as you've done in
the
second statement above. This, the whole function body could be
written:
o << static_cast<Person&>(emp)
<< std::endl << "Started: " << emp.m_startDate
<< " Role: " << emp.m_job << "Dept: " << emp.m_department
<< std:: endl; << "Salary: " << emp.m_salary << std::endl;
Hope this helps.
--Nick