1

The full code looks like this:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

class Point {
double x;
double y;
public:
Point();
Point(int x, int y);
void setPoint(int x, int y);
int getX(void)const;
int getY(void)const;
Point operator + (const Point & point);
Point& operator=(const Point& point);
};

ostream& operator<<(ostream& os, const Point& point) {
 os << point.getX() << " ," << point.getY();                    
 return os;
}

Point::Point() {
x = y = 0;
}
Point::Point(int x, int y) {
this->x = x;
this->y = y;
}
void Point::setPoint(int x, int y) {
this->x = x;
this->y = y;
}
int Point::getX(void)const {
return this->x;
}
int Point::getY(void)const {
return this->y;
}
Point Point::operator+(const Point& point) {
Point result(this->x + point.getX(), this->y + point.getY());
return result;
} 
Point& Point::operator=(const Point& point) {
this->x = point.getX();
this->y = point.getY();
return (*this);
}
int main() {
Point a(1, 2);
cout << a << endl;
}

In the following part

ostream& operator<<(ostream& os, const Point& point) {
 os << point.getX() << " ," << point.getY();    
 return os;         
}

If the return type is ostream, a red line appears. I am not sure what the difference between return type is ostream & and ostream. I'd appreciate it if you explained

*For reference, I forgot to return os, so I edited the post

  • 1
    The issues with slicing aside, returning by value is making a copy. Think about what it means to copy a stream -- copying a file stream might make sense since there is `dup()`. But what would it mean to copy a stream backed by a TCP stream? Maybe there are types of streams that can't be copied... so we can't allow it in the general case. – cdhowie May 23 '20 at 08:03

2 Answers2

2

The ostream object cannot be copied as the copy constructor of ostream object is deleted. That is why one needs to pass the ostream object by reference.

Pro tip: Ever wondered why we need to return ostream& if it was already passed by reference?

kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39
2

If you would return an ostream then you would have slicing. In case the passed os was an ofstream then the returned ostream would only be the ostream part of the ofstream and not the full ofstream. When returning by reference you don't have slicing and don't lose information about the full type of the stream.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
  • Thanks! I think I lack understanding of streams. I'll study more. Could you give me some reference material? Thanks for the reply –  May 23 '20 at 07:56
  • @bongbong, Go no further than [SO](https://stackoverflow.com/questions/45172025/about-stdostream-constructor?rq=1) – kesarling He-Him May 23 '20 at 07:57