Reputation: 5
We have the following situation:
In Classes A and B, we have overridden the <<
operator.
Now, we have a new class C with data members of objects of A and B.
How would we override the <<
operator here?
To be more specific,
We need something like this:
cout<<objectOfC
corresponds to cout<<correspondingObjectOfA<<correspondingObjectOfB
I'm not getting how to modify the ostream& object so as to return it back.
ostream& operator<< (ostream& out, const C& obj){ // This is a friend function declared in C.h
A* a = obj.AObject; // Returns the corresponding object of A
B* b = obj.BObject; // Returns the corresponding object of B
// Need to modify out somehow to 'cout' A and B respectively when cout is called on an object of C
return out;
}
Any help would be greatly appreciated. Thank you :)
Upvotes: 0
Views: 88
Reputation: 5565
If you already have appropriate overrides for A
and B
, just use them.
ostream& operator<< (ostream& out, const C& obj) {
out << *obj.AObject << *obj.BObject;
return out;
}
Because operator<<
returns its ostream
argument, you can further condense this:
ostream& operator<< (ostream& out, const C& obj) {
return out << *obj.AObject << *obj.BObject;
}
Upvotes: 1