1

I'm a C++ beginner, trying to learn from online videos. In of the operator overloading examples in the lectures the following code is there and gives the error

 error: no match for 'operator<<' in 'std::cout << operator+(((point&)(& p1)), ((point&)(& p2)))'compilation terminated due to -Wfatal-errors.

on the line marked with comment. Can someone please tell what's wrong in the code? I am just trying what the professor explained in the lecture but can't compile.

===============

#include <iostream>
using namespace std;


class point{
public:
    double x,y;
};

point operator+ (point& p1, point& p2)
{
    point sum = {p1.x + p2.x, p1.y + p2.y};
    return sum;
}

ostream& operator<< (ostream& out, point& p)
{
    out << "("<<p.x<<","<<p.y<<")";
    return out;
}


int main(int argc, const char * argv[])
{
    point p1 = {2,3};
    point p2 = {2,3};
    point p3;
    cout << p1 << p2;

    cout << p1+p2; // gives a compliation error
    return 0;
}
0

3 Answers 3

3

It's just a problem with const correctness. Your operator+ returns a temporary, so you can't bind a non-const reference to it when calling operator<<. Make the signature:

ostream& operator<< (ostream& out, const point& p)

While you don't need to do it to fix this compilation error, you won't be able to add const points unless you fix the operator+ similarly:

point operator+(const point& p1, const point& p2)
Sign up to request clarification or add additional context in comments.

3 Comments

"Your operator+ returns a temporary, so you can't bind a non-const reference to it when calling operator<<" - That is not obvious. Is it somewhere in the C++ standard?
Thanks Tony for the detailed explanation.
@SergiiKhaperskov: it's covered in 8.5.3/5, see "Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be const), or the reference shall be an rvalue reference." and the example "double& rd2 = 2.0; // error: not an lvalue and reference not const".
0

Change the parameter type from point& to const point& for operator+ and operator<<. Non-const reference cannot bind to a temporary (which is returned by operator+) and that is causing the compile error.

Comments

0

The reason is the second parameter should be a const reference. (you don't want it gets modified, right?) So, it is like,

std::ostream& operator<< (std::ostream &out, const Point &p)
{
    out << "(" << p.x << ", " << p.y << ")";

    return out;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.