Andy
Andy

Reputation: 51

C++ << operator overloading without friend function

Exactly as the topic says. Is there a possibility to do that? I was able to achieve this in overloading '+' operator, however, I could not do this with '<<' operator.

This is an example of code that works for me with friend function:

class Punkt2D
{
    int x,y;

    public:
        Punkt2D(int wartoscX, int wartoscY) : x(wartoscX), y(wartoscY) {}
        friend ostream& operator<<(ostream& out, Punkt2D& punkt);
};

ostream& operator<<(ostream& out, Punkt2D& punkt)
{
    out << "(" << punkt.x << ", " << punkt.y << ")" << endl; 
    return out;
}

int main()
{
    Punkt2D p1(10,15);

    cout << p1 << endl;
    return 0;
}

I tried this code on '+' without befriending the function. Is it also possible for other operators? Maybe it is a silly question, however I am quite new to C++ and could not find any resource on the topic :(

class Vector
{
    public:

    double dx, dy;
    Vector() {dx=0; dy=0;}
    Vector(double x, double y) 
    {
        cout << "Podaj x " << endl;
        cin >>x;
        cout << "Podaj y " << endl;
        cin >> y;
        dx = x; dy = y;

    }
    Vector operator+ (Vector v);
};


Vector Vector::operator+ (Vector v)
{
    Vector tmpVector;
    tmpVector.dx = dx +v.dx;
    tmpVector.dy = dy+ v.dy;
    return tmpVector;
}

int main()
{
    double d,e;

    Vector a(d,e);
    Vector b(d,e);
    Vector c;
    c = a +b;
    cout<<endl << c.dy << " " << c.dx;
    return 0;
}

Upvotes: 2

Views: 4763

Answers (3)

Chandan K Singh
Chandan K Singh

Reputation: 96

The stream operators:

operator << output
operator >> input

When you use these as stream operators (rather than binary shift) the first parameter is a stream. Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you.

Upvotes: 1

Peter
Peter

Reputation: 36597

As long as the function only calls public member functions of the class (or accesses public data members, if any) it does not need to be a friend.

Your Vector example is only accessing public members, hence it works.

Your Punkt2D is accessing private members, so the operator needs to be a friend.

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92211

It needs to be a friend to access the private members.

In the Vector the members are public, so that's different.

Upvotes: 1

Related Questions