C++: Friend Class

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

A class can be allowed to access the private and protected members of another class by declaring the class a friend.

The friend is allowed to access all members in the class where the friend is defined, but not the other way around.

Consider the following example.

In the class Music, we declare Rock to be a friend of Music.  Now Rock class could access the private members of Music such as singer and title.

#include <iostream>

using namespace std;

class Music {

    void setSinger(string s) {
        singer = s;

    void setTitle(string t) {
        title = t;

    string singer;
    string title;

    friend class Rock;

class Rock {

    int Print(Music m) {

        cout << m.singer << " singing " << m.title;
        return 0;

int main(void) {

    Rock rock;
    Music music;

    music.setSinger("Rod Stewart");


    return 0;


Series Navigation<< C++: Friend functions
C++: Static variable >>

Leave a comment

Leave a Reply