Search code examples
c++encapsulationfriendaccess-control

C++: friend function passing to non-friends


Doesn't this break encapsulation?

B.h:

class B{
    int x, y;
public:
    B() : x(1), y(1) {}
    B(const B& obj) : x(obj.x), y(obj.y) {}

    int getx();
    int gety();

    friend void pass_private_members(B&);
};

B.cpp

void non_friend_pass_private_members(int& x);

int B::getx(){
    return this->x;
}

int B::gety(){
    return this->y;
}

void pass_private_members(B& obj){
    non_friend_pass_private_members(obj.x);
}

void non_friend_pass_private_members(int& x){
    x++;
}

main.cpp

int main(){
    B obj;
    pass_private_members(obj);
    cout << obj.getx() << endl;
    return 0;
}

Solution

  • By declaring friend void pass_private_members(B&) you are telling compiler you trust the pass_private_members to handle the private members of B. What it does with the private members is not of compiler's concern. This is no different from having a member function which calls the non_friend_pass_private_members.