'Why do we return by value while implementing cascading of cin cout?
This is a code to print/input the linked list by overloading cin/cout. Why is the return type ostream& in place of just ostream?
ostream& operator<<(ostream& os, node* head)
{
print(head);
}
// Overloading the istream operator '>>' to take continuous input into the linked
istream& operator>>(istream& is, node*& head)
{
takeInput(head);
}
// Driver Code
int main()
{
node* head = NULL;
// input linked list
cin >> head;
// print linked list
cout << head;
return 0;
}
Solution 1:[1]
It's because by default, c++ returns a copy of a variable. So ostream will be a copy, while ostream& will be a reference. References are commonly used in c++ for this reason and to save performance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stefanarctic |
