Unit 15: Friends

  1. Friends!

  2. Example code and additional resources

This week's stuff:

Friends!

Remember that a class can define its member functions and variables as either:

  • public, so that everything inside and outside of the class can access those members.
  • private, where only the class' member functions can access its private members.
  • protected, where any inherited classes (children, descendants) and the class itself can access these members.

However, we could also define a function or another class as a friend. Doing this gives the friend access to the private/protected member variables and functions of the one declaring the friendship (the friendship does not automatically go both ways.)


To specify who is a friend of the class we're declaring, we use a forward declaration, but with the friend keyword:

// ... within a class declaration...
private:
friend void Process();
friend class Tester;
// ...

Example code and additional resources

Example code: (repository)