Online Courses
Free Tutorials  Go to Your University  Placement Preparation 
0 like 0 dislike
5k views
in JECRC University B.Tech(CSE-III Sem) Object Oriented Programming Lab by Goeduhub's Expert (7.1k points)

Stream Insertion and Stream Extraction Operator Overloading

Goeduhub's Top Online Courses @Udemy

For Indian Students- INR 360/- || For International Students- $9.99/-

S.No.

Course Name

 Coupon

1.

Tensorflow 2 & Keras:Deep Learning & Artificial Intelligence || Labeled as Highest Rated Course by Udemy

Apply Coupon

2.

Complete Machine Learning & Data Science with Python| ML A-Z Apply Coupon

3.

Complete Python Programming from scratch | Python Projects Apply Coupon
    More Courses

1 Answer

0 like 0 dislike
by Goeduhub's Expert (7.1k points)
edited by
 
Best answer

Stream Insertion and Extraction Operator Overloading

In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.

As we all know cout is an object of ostream class and cin is an object of istream class. Insertion and extraction operators functions must be overloaded as global functions. And if we want to allow them to access private data members of class, we must make them friend.

Why to Overload << and >>

If we do not overload insertion and extraction operators and we insert or extract any object as below given example

#include<iostream.h>
class Hey
{
private:
int x;
};
void main()
{
Hey h;

// It will generate compilation error
cin>>h;
cout<<h;
getch();
}

Clearly this will generate compilation error as an object of any class can not be inserted or extracted. To overcome this issue we overload these operators.

Insertion and extraction operators can not be a member of any class as cin and cout are not objects of that class. So these functions must be global functions and to access private members of the class these must be declared friend.

Example

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Check
{
private:
float x,y;

//Declaring insertion and extraction operators as friend of class Check
friend istream& operator >>(istream&,Check&);
friend ostream& operator <<(ostream& output,Check& obj);
};

//Defining insertion and extraction operators
istream& operator >>(istream& input,Check& obj)
{
input>>obj.x>>obj.y;
return input;
}
ostream& operator <<(ostream& output,Check& obj)
{
output<<"\nx:"<<obj.x<<" y:"<<obj.y;
return output;
}
void main()
{
clrscr();
Check c;
cin>>c;
cout<<c;
getch();
}

Output

10
20
x:10 y:20

For more Object Oriented Programming Lab Experiments Click Here

3.3k questions

7.1k answers

394 comments

4.6k users

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...