← C++ from Scratch Lesson 41 of 62 · 10 XP

Friend functions

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

friend gives a separate function (or class) access to the private fields:

class Vec2 {
public:
    Vec2(int x, int y) : x_(x), y_(y) {}
    friend std::ostream &operator<<(std::ostream &out, const Vec2 &v);   // a friend
    friend Vec2 operator+(const Vec2 &a, const Vec2 &b);
private:
    int x_, y_;
};

std::ostream &operator<<(std::ostream &out, const Vec2 &v)
{
    return out << '(' << v.x_ << ", " << v.y_ << ')';
}

The most common case is operator overloading for output << and arithmetic: then std::cout << v and a + b work with your class as if it were a built-in type. friend breaks encapsulation at one specific point — give it only to the functions that are, in meaning, part of the class's interface.

Task. A class Vec2 with private x, y and friend functions operator+ and operator<< (the format (x, y)). Read n vectors and print their sum.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.