25-Comp-B11 Advanced Software Design · December 2018
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer) · Last updated
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.
friend grants a function or class direct ACCESS to another class's private/protected members, bypassing the encapsulation boundary (Question 23) the class's public interface would otherwise enforce.
Pro 1 — performance. Tightly-coupled, performance-critical code accesses the internal representation directly rather than through possibly-virtual public accessor calls. Example: a Matrix multiplication kernel declared as a friend function of Matrix can read the raw internal array directly, avoiding a getter call per element in a hot inner loop.
Pro 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, not the object), so it needs friend access to print the object's private state directly. Example: friend ostream& operator<<(ostream& os, const Point& p) prints p's private x/y without needing public getters that would otherwise exist solely for this one purpose.
Con 1 — breaks information hiding (Question 23). A friend can read AND WRITE the class's internal representation directly, so the class's actual invariant-preserving interface silently expands to include every friend, not just its declared public methods. Example: if Matrix's internal array layout later changes from row-major to a sparse representation, every friend function that read the raw array directly must also be found and rewritten, unlike a change kept behind accessor methods, which by definition cannot break well-behaved external callers.
Con 2 — scattered, hard-to-audit access. friend declarations sit far from the class's own call sites, so determining "who can affect this class's invariants" requires a whole-codebase search. Example: a maintainer changing BankAccount's private balance-tracking field must also locate and review every class/function declared as a friend anywhere in the codebase, not just the class's own listed public methods.
Conclusion. friend is a deliberate, narrow escape hatch traded against modularity for a measured performance or syntax need — used sparingly (operator-overload pairs, tightly-coupled iterator/container pairs), never as a routine substitute for a proper public interface.