kaushal
kaushal

Reputation: 815

<< Operator overloading error in C++

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;
}

Upvotes: 1

Views: 93

Answers (3)

liuyruc
liuyruc

Reputation: 301

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;
}

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106068

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)

Upvotes: 3

neverhoodboy
neverhoodboy

Reputation: 1050

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.

Upvotes: 0

Related Questions