25-Comp-B11 Advanced Software Design · December 2019
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer)
friend Access in C++ — Advantages, Disadvantages, and Why Java Disallows It (Part V)Question text not reproduced: the examination questions are © Engineers and Geoscientists BC. Open the official past paper (linked at the top of this page) to read the question, then follow the worked solution below.
class Matrix {
private:
double data[100][100];
friend Matrix multiply(const Matrix& a, const Matrix& b); // grants direct access
};
Matrix multiply(const Matrix& a, const Matrix& b) {
// reads a.data / b.data directly -- no accessor call needed
}
friend grants a named function or class direct access to another class's private/protected members, bypassing the encapsulation boundary (Question 23) the public interface would otherwise enforce.
Advantage 1 — performance. A tightly-coupled, performance-critical function (like the matrix multiplication above) reads the internal representation directly instead of through a getter call per element in a hot inner loop.
Advantage 2 — natural syntax for symmetric operators. operator<< for stream output cannot be a member function of the class being printed (the left-hand operand must be the stream), so it needs friend access to print the object's private state directly, e.g. friend ostream& operator<<(ostream& os, const Point& p).
Disadvantage 1 — breaks information hiding. A friend can read AND write the class's internals directly, so the class's real invariant-preserving boundary silently expands to include every friend, not just its own public methods; if Matrix's internal layout later changes, every friend function must also be found and rewritten.
Disadvantage 2 — scattered, hard-to-audit access. friend declarations sit far from the class's own methods, so answering "who can affect this class's invariants" requires a whole-codebase search rather than reading one class body.
Why Java disallows it. Java instead standardizes on package-private visibility (Question 23) as the one controlled relaxation of private, keeping access control fully local to the declaring class body and predictable from a single file, rather than granting bespoke, class-by-class exceptions declared inside the class being exposed. This trades C++'s finer-grained, per-relationship control for a simpler, more uniformly auditable rule.