Friendship in C++

Hi,

C++ allows users to define a “friendzone” comprised by functions or classes. The purpose of a friend in C++, is to make private and protected section, be accessible by the portion out of that section (scope of the code).

In other words:

In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not apply to ‘friends’” (cplusplus.org)

A friend class in C++ can access the “private” and “protected” members of the class in which it is declared as a friend” (Wikipedia)

Simple example (original here):

class B {
    friend class A; /* A is a friend of B */
 
private:
    int i;
protected:
    int j;
public:
    int p;
};
 
class A {
public:
    A(B b) {
        b.i = 0; /* legal access due to friendship */
        b.j = 0; /* legal access due to friendship */
        b.p = 0; /* legal access, but it is not because of friendship. 
                    Is accessible because the function is defined as public within B */
    }
};

Object B has a private member named “i”, which could only be accessible by functions defined within the class A, if A wasn’t a friend of B. Thus, A (is a friend of B) can access everything of B.

That’s all,

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s