Question

I have defined a point class using dev c++. then I tried to overload cout for this class. while not using it i get no error. but when i use it in main it gives me this error:

[Linker error] C:\Users\Mohammad\Desktop\AP-New folder\point/main.cpp:12: undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Point const&)' 

//point.h

    class Point{
private:
    double x;
    double y;
    double z;
public:

    //constructors:
    Point()
    {
    x=0;
    y=0;
    z=0;
    }
    Point(double xx,double yy,double zz){x=xx; y=yy; z=zz;}

    //get:
    double get_x(){return x;}
    double get_y(){return y;}       
    double get_z(){return z;}

    //set:
    void set_point(double xx, double yy, double zz){x=xx; y=yy; z=zz;}

    friend ostream &operator<<(ostream&,Point&);

};

    //point.cpp
    ostream &operator<<(ostream &out,Point &p){
        out<<"("<<p.x<<", "<<p.y<<", "<<p.z<<")\n";
        return out;

}

//main.cpp

    #include <iostream>
    #include "point.h"

    using namespace std;

    int main(){

Point O;
cout<<"O"<<O;


cin.get();
return 0;

}

Was it helpful?

Solution

This is because you did not make your Point a const when declaring and defining your operator. Change your declaration as follows:

friend ostream &operator<<(ostream&, const Point&);

Also add const in the definition:

ostream &operator<<(ostream &out, const Point &p){
    out<<"("<<p.x<<", "<<p.y<<", "<<p.z<<")\n";
    return out;
}

Note that the code that you posted does not require const-ness of the Point&. Some other code made your compiler or IDE believe that an operator with a const is referenced. For example, using the operator like this would require a const

cout << Point(1.2, 3.4, 5.6) << endl;

(demo)

Since the snippet above creates a temporary object, passing a reference to it as a non-const is prohibited by the C++ standard.

Not directly related to this issue, but you may want to mark the three getters for individual coordinates const as well:

double get_x() const {return x;}
double get_y() const {return y;}       
double get_z() const {return z;}

This would let you access coordinates with getters on objects marked const.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top