Overloading Stream Operators

Introduction

C++ में cin और cout का उपयोग input और output के लिए किया जाता है। ये stream objects होते हैं और इनके साथ >> (extraction operator) और << (insertion operator) का उपयोग किया जाता है।

जब हम user-defined data types (class objects) के साथ काम करते हैं, तो default रूप से cin और cout उन objects को handle नहीं कर पाते। इसलिए हमें इन operators को overload करना पड़ता है, ताकि objects को आसानी से input और output किया जा सके।

Definition

Stream Operator Overloading वह प्रक्रिया है जिसमें << और >> operators को user-defined types (class objects) के लिए redefine किया जाता है, ताकि objects को input और output किया जा सके।

Basic Concept

  • cout << object → object को print करने के लिए
  • cin >> object → object में input लेने के लिए

इन operators को overload करने के लिए friend function का उपयोग किया जाता है।

क्यों Friend Function?

  • cout और cin पहले operand होते हैं
  • इसलिए operator function class के अंदर member function के रूप में define नहीं किया जा सकता
  • इसीलिए friend function का उपयोग किया जाता है

Syntax

Insertion Operator (<<)

friend ostream& operator<<(ostream &out, ClassName &obj);

Extraction Operator (>>)

friend istream& operator>>(istream &in, ClassName &obj);

Example (<< और >> Overloading)

#include <iostream>
using namespace std;

class Student {
private:
string name;
int age;

public:
friend ostream& operator<<(ostream &out, Student &s);
friend istream& operator>>(istream &in, Student &s);
};
// output operator
ostream& operator<<(ostream &out, Student &s) {
out << "Name: " << s.name << endl;
out << "Age: " << s.age;
return out;
}
// input operator
istream& operator>>(istream &in, Student &s) {
cout << "Enter Name: ";
in >> s.name;
cout << "Enter Age: ";
in >> s.age;
return in;
}

int main() {
Student s1;

cin >> s1;
cout << s1;

return 0;
}

Output:

Enter Name: Rahul
Enter Age: 20
Name: Rahul
Age: 20

Working को समझना

  • cin >> s1 → overloaded >> function call होता है
  • cout << s1 → overloaded << function call होता है
  • friend function private data को access कर पाता है
  • return out और return in chaining के लिए जरूरी है

Important Points

  • << → output के लिए
  • >> → input के लिए
  • friend function का उपयोग किया जाता है
  • return type reference (&) होता है

Chaining Example

cout << s1 << s2;

यह तभी संभव है जब हम return out; करते हैं।

निष्कर्ष

Stream operator overloading C++ में objects के साथ input और output operations को आसान बनाता है। यह code को अधिक readable और user-friendly बनाता है और OOP के साथ seamless integration प्रदान करता है।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top