With inheritance, I'm trying to create an overloaded output operator in my base class that calls an output function in the proper derived class to print the correct data based on which type of object.
How do you return an output that can be sent into an overloaded output operator so you can output the object with just cout << object << endl;
For instance:
ostream & operator<< (ostream &out, const person &rhs){
out << rhs.print_data();
return out;
}
ostream student::print_data(){
ostream out;
out << data;
return out;
}
ostream faculty::print_data(){
ostream out;
out << data;
return out;
}
EDIT: I'm trying to figure out if I need to return type ostream
or ostream &
in the print functions
Streams can not be copied, so if you want to return (or pass as argument) it must be done by reference. And you can't return a reference to a local variable (as those will go out of scope and "disappear").
Besides, a basic std::ostream
object doesn't make sense to create instances of.
Simple solution: Pass the stream as argument (by reference of course) to the functions:
ostream& operator<< (ostream &out, const person &rhs){
return rhs.print_data(out); // No need for any output here
}
ostream& student::print_data(ostream& out){
return out << data;
}