C++: Friends

Friends are external classes that is given permission to access private/protected members of this class.

---- Scenario 1: Friend functions ----

class apples{
    private:
        friend func();
};
class oranges{
    void foo();
};
void oranges::foo() {
    apples* a = new apples();
    a->func();        // this is ok because func is a friend
}

---- Scenario 2: Friend classes ----

class apples{
    friend class oranges;
    private:
        int value;
};
class oranges{
    void foo();
};
void oranges::foo(){
    apples* a = new apples();
    a->value = 10;        // this is ok because oranges is declared as a friend of apples
}

No comments: