#include <iostream>
using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
**friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);**
};
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
istream & operator >> (istream &in, Complex &c)
{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imagenory Part ";
in >> c.imag;
return in;
}
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
What is the use of passing the operator as a reference "& operator".
When we pass a normal operator we never pass the reference, but in the above code, we are passing the reference to the operator.
Can anyone explain the part where operator reference is passed?
In the code friend ostream & operator << the & is associated with the type overloaded operator returns.
So that it returns ostream & and istream & for the second one.
The overloaded operators:
Take the reference to istream or ostream object whcih is I/O object like cin/cout for console I/O or other type of stream object (I/O from/to string, etc).
Affect the state of the object so that data is read/written.
Return the reference to that object so that you can use these operators in sequence like:
Complex c1
Complex c2;
cin >> c1 >> c2;
Generally if a Declare one name (only) per declaration rule is adhered to,
then this allows to consistantly write a pointer/refrence "stuck" next to the type as:
istream& operator>> (istream& in, Complex& c)
{ //...
In this way it can be seen that the function named operator>> is returning a type istream& (a reference to an istream object).
This function takes 2 variables:
in of the type istream& (a reference to an istream object),
c of the type Complex& (a reference to a Complex object).
and similarly for:
ostream& operator<< (ostream& out, const Complex& c)
{ //...
The formatting of the code does not in anyway affect how the code is compiled.
So the functions definitions in this answer are exactly the same as in the question.
As to why use a reference, I suggest to read: When to use references vs. pointers
Related
Reading some documentation online I found that istream class was part of C++ long before the string class was added. So the istream design recognizes basic C++ types such as double and int, but it is ignorant of the string type. Therefore, there are istream class methods for processing double and int and other basic types, but there are no istream class methods for processing string objects.
My question is if there are no istream class methods for processing string objects, why this program works and how ?
#include <iostream>
int main(void)
{
std::string str;
std::cin >> str;
std::cout << str << std::endl;
return 0;
}
This is possible with the use operator overloading. As shown in the below example, you can create your own class and overload operator>> and operator<<.
#include <iostream>
class Number
{
//overload operator<< so that we can use std::cout<<
friend std::ostream& operator<<(std::ostream &os, const Number& num);
//overload operator>> so that we can use std::cin>>
friend std::istream &operator>>(std::istream &is, Number &obj);
int m_value = 0;
public:
Number(int value = 0);
};
Number::Number(int value): m_value(value)
{
}
std::ostream& operator<<(std::ostream &os, const Number& num)
{
os << num.m_value;
return os;
}
std::istream &operator>>(std::istream &is, Number &obj)
{
is >> obj.m_value;
if (is) // check that the inputs succeeded
{
;//do something
}
else
{
obj = Number(); // input failed: give the object the default state
}
return is;
}
int main()
{
Number a{ 10 };
std::cout << a << std::endl; //this will print 10
std::cin >> a; //this will take input from user
std::cout << a << std::endl; //this will print whatever number (m_value) the user entered above
return 0;
}
By overloading operator>> and operator<<, this allows us to write std::cin >> a and std::cout << a in the above program.
Similar to the Number class shown above, the std::string class also makes use of operator overloading. In particular, std::string overloads operator>> and operator<<, allowing us to write std::cin >> str and std::cout << str, as you did in your example.
Because std::string overload the >> and << operator to return the type std::istream and std::ostream
How they overload it, you can look in this link that Mat gives.
You can create your own class and overload operators, too. Here is an example:
class MyClass
{
int numberOne;
double numberTwo;
public:
friend std::ostream& operator<<(std::ostream &out, const MyClass& myClass);
friend std::istream& operator>> (std::istream& in, MyClass& myClass);
};
// Since operator<< is a friend of the MyClass class, we can access MyClass's members directly.
std::ostream& operator<<(std::ostream &out, const MyClass& myClass)
{
out << myClass.numberOne << ' ' << myClass.numberTwo;
return os;
}
// Since operator>> is a friend of the MyClass class, we can access MyClass's members directly.
std::istream& operator>> (std::istream& in, MyClass& myClass)
{
in >> myClass.numberOne;
in >> myClass.numberTwo;
return in;
}
int main()
{
MyClass myClass;
std::cin >> myClass;
std::cout << myClass;
}
Because of operator overloading.
In your case, including <iostream> will include <string>, a specialization of std::basic_string. And std::basic_string has the non-member functions operator<< and operator>> defined.
Similarly, you can also overload operator<< and operator>> for your own custom types.
Stuck with ostream/istream operator overloading
Q1. why we are using ostream& operator as friend?
Q2. Why we are passing two arguments in ostream & operator << (ostream &out, const Complex &c)
Q3. why we are referencing to Cout and in ? istream & operator >> (istream &in, Complex &c).
Ref to: Overloading stream Oerator overloading- Geeks4Geeks
HERE IS THE CODE
#include <iostream>
using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);
};
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
istream & operator >> (istream &in, Complex &c)
{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imaginary Part ";
in >> c.imag;
return in;
}
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
A1. To access the private members
A2. The first argument is the stream and the second is the object. operator<< and operator>> expect two arguments
A3. Because they are modified in the function. The functions read from resp. write into the stream.
In addition:
Don't use using namespace std;
Don't initialize members in the constructor body. Use the constructor initializer list
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
should be
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
The purpose of program is to take input, assign those values to the members of the class and display the output, with the input and output operation being done by overloading stream operators.
#include <iostream>
using namespace std;
class MyClass {
int x, y;
public:
MyClass(int i, int j) {
x = i;
y = j;
}
friend ostream& operator<<(ostream &stream, MyClass ob);
friend istream& operator>>(istream &stream, MyClass &ob);
// friend void operator<<(ostream &stream, MyClass ob);
// friend void operator>>(istream &stream, MyClass &ob);
};
ostream& operator<<(ostream &stream, MyClass ob)
{
stream << ob.x << ' ' << ob.y << '\n';
return stream;
}
istream& operator>>(istream &stream, MyClass &ob)
{
stream >> ob.x >> ob.y;
return stream;
}
int main()
{
MyClass abt(30,23);
cin>>abt;
cout<<abt;
return 0;
}
In the example, if data is taken from input stream 'cin' and the values are assigned inside the function, why should 'istream' be returned back. I have seen all tutorials return stream in operator overloading function. What is the purpose of return value?
In the example, if data is taken from input stream cin and the values are assigned inside the function, why should istream be returned back?
This is done to allow "chaining".
The operator takes its two parameters from both sides of >>. The stream comes from the left, and the variable comes from the right. When you do this
cin >> x >> y;
the first expression cin >> x is on the left of the second expression, which means that the result of cin >> x becomes ... >> y's input stream. That is why the operator needs to return the same input stream that has been passed into it.
How do you suppose the following works?
stream >> ob.x >> ob.y;
That's exactly the same as:
(stream >> ob.x) >> ob.y;
So what's the value of stream >> ob.x?
"What is the purpose of return value?"
The purpose is, that these operations can be chained in statements like
MyClass abt(30,23);
int y;
cout << abt << endl;
// ^^^^^^^
cin >> abt >> y;
// ^^^^
cout and cin are linked with each other through <iostream> the child class of istream and ostream. Now as we are about to overload operators as a global functions because overloading as a member the operator must be the member of the object on the left hand side. Also to make the function of the generic streams we have to pass the references and not values. So we have to opt for overloading them with friend function.
Hence:
istream & operator>>(istream &din,vector &vtemp)
Now the din will work similar to cin as din has a reference to cin. Now using din we scan the data-members of the object. After scanning we have to chain them (streams). So reference must be returned to cin.
I'm currently working on a C++ assignment and I have 3 different types of objects. Customer, Hire and Tour. When I create a object now I do the following, I read the data from a file and then do the following,
Customer* cust = new Customer(custId, Name, ...);
However the requirement is to use >> operators to read this information into objects. Also use << write it back. How can I achieve this?
Many thanks :)
First of all, there is likely no need for your to create objects on the heap.
After you've made those corrections, you can overload the insertion and extraction operators:
// assuming you declare these operators as friends of Customer
std::ostream& operator<<(std::ostream& os, const Customer& c)
{
os << c.data;
return os;
}
std::istream& operator>>(std::istream& is, Customer& c)
{
is >> c.data;
return is;
}
Well here is a really good reference (apparently not that good because I had to fix some of the code) for overloading the io operators. I can't tell you much more with out knowing the details of your class, however I can say that the beauty of the stream operators is that they provide an interface to any stream type object not just stdin and stdout. Here is a little example from the site:
#include
using namespace std;
class Point
{
private:
double m_dX, m_dY, m_dZ;
public:
Point(double dX=0.0, double dY=0.0, double dZ=0.0)
{
m_dX = dX;
m_dY = dY;
m_dZ = dZ;
}
friend ostream& operator<< (ostream &out, Point &cPoint);
friend istream& operator>> (istream &in, Point &cPoint);
double GetX() { return m_dX; }
double GetY() { return m_dY; }
double GetZ() { return m_dZ; }
};
ostream& operator<< (ostream &out, Point &cPoint)
{
// Since operator<< is a friend of the Point class, we can access
// Point's members directly.
out << cPoint.m_dX << " " << cPoint.m_dY << " " << cPoint.m_dZ << std::endl;
return out;
}
istream& operator>> (istream &in, Point &cPoint)
{
in >> cPoint.m_dX;
in >> cPoint.m_dY;
in >> cPoint.m_dZ;
return in;
}
IMO the best way to think about overloading these operators is to leverage previously written >> and << and that way you sort of build a chain and it becomes extremely simple and convenient to implement these operators.
I have doubt in my mind regarding declaration of cin and cout object . As per my understanding cin and cout both object are accessible in main then they shouldn't have protected.in below code snippet i have overloaded both input and output operator and
while giving new name (ofstream obj) to user defined version of this operator , I am getting error like obj is protected and can't be accessed here. Anybody can suggest .
#include<iostream>
using namespace std;
class overload
{
public:
int var_a;
overload (int fun_a=10): var_a(fun_a) {}
friend ostream operator >> (ostream &output, overload &);
friend istream operator << (istream &input, overload &);
};
ostream &operator <<( ostream &output, overload &s1)
{
output<<"value of object output:"<<s1.var_a<<endl;
return output;
}
istream &operator >>( istream &input, overload &s1)
{
input >> s1.var_a;
return input;
}
int main()
{
overload s1,s2;
//ostream obj;
//obj<<"enter the value of object"
cout<<"enter the value of object";
cin>>s2;
cout<<s2;
return 1;
}
The relevant part is the & in ostream &. That makes it a reference.
In your main(), you can in fact do the same: ostream& obj = std::cout;. Just like the ostream& output in operator<< is valid while that function runs, ostream& obj will be valid while the main function runs.
[edit]
As for your comment, that's missing a critical point. std::cout is an std::ostream, yes. But std::ofstream (file) also is an std::ostream. Wait, you may say, one type is another type? Yes, in OO languages. Inheritance means that each object has the type used to construct it, but also any base types inherited from.
That's why you can pass a file stream to your operator<< overload. The std::ostream& can be initialized with any derived object.