C++: Friend functions

This entry is part 59 of 61 in the series C++

Sometimes, you might have an independent function and you might want this function to access the private members of a class.

You can declare this independent function as friend of the class. A friend can access any of the members of a class object, regardless of their access specification.

In the example below, we have an independent function called CurrentWeek.  We have declared CurrentWeek within the Album class that it is a friend function.

With this declaration, the function can access the private variable top10 of the Album class.

#include <iostream>

using namespace std;

class Album {
    
private:
    int top10;

public:

    Album(void) : top10(0) {

    }

    void show(void) {

        cout << top10 << endl;
    }

    friend void CurrentWeek(Album &);

};

void CurrentWeek(Album &alb) {

    alb.top10 = alb.top10 + 5;
}

int main() {

    Album album;
    album.show();

    CurrentWeek(album);
    album.show();

}

friend

Series Navigation<< C++: Pure virtual function turns a class into abstract class
C++: Friend Class >>