If a Manager class is created as a subclass of Employee, do we need to write another operator<<?
That is, do we need both of these:
1. ostream operator<<(ostream& os, const Employee& e) 2. ostream operator<<(ostream& os, const Manager& m)
Answer: No, provided some conditions are met:
- We implement a public Employee virtual method that returns a string representation of Employee; for example, a toString() method.
- We implement the operator<< using this toString()
method:
Defined in Employee.cpp #include "Employee.h" ostream operator<<(ostream& os, const Employee& e) { os << e.toString(); return os; }
- We override toString() in the Manager subclass of Employee to print a representation of a Manager instance.
Then a Manager instance can be passed to the operator<< already written for Employee and the e.toString() will use Manager's implementation of toString().