Private data keeps the rest of a program from bypassing an object's rules. Normally, public member functions are the right way to offer useful operations. Occasionally a tightly related non-member function needs direct access to the representation. A class can grant that specific function access with a friend declaration.
A friend function is not a member function. Call it as readCode(label), not label.readCode(). Write its declaration inside the class with the word friend, then define the ordinary function outside the class. The class controls which function receives this permission; outside code cannot simply declare itself trusted.
Friend access is powerful: it permits access to private members, so a function that changes them must preserve the same invariants as the class's own methods. Do not use friendship as a shortcut for making every field public. A const reference parameter is a useful limit for a read-only helper: it borrows an object without copying it and cannot modify its ordinary members through that parameter.
#include <iostream>
class Label {
private:
int code;
public:
Label(int value) : code(value) {}
friend int readCode(const Label& label);
};
int readCode(const Label& label) { return label.code; }
int main() {
const Label label(17);
std::cout << readCode(label) << '\n';
}
The example prints 17. The declaration inside Label grants access; the definition outside it does the reading. Find the same two parts for headcount in the starter. The declaration is complete, so edit the function body below the class. Because it is not a member function, it names the object explicitly when reading each field. This exercise shows how friendship works; a const member query is usually enough for a simple report like this.
headcount() by returning attendance.adults + attendance.children. Leave both fields private and the parameter read-only. The probe should print Headcount: 19.Edit main.cpp, then press Run to inspect the Console. Press Submit to check your work. Keep the supplied probes in place.