Friend Classes
A friend class is a class whose member functions can access private and protected members of another class.
Example
#include <iostream>
class Engine;
class Car {
private:
bool running = false;
public:
friend class Engine;
void status() const {
std::cout << (running ? "Running\n" : "Off\n");
}
};
class Engine {
public:
void start(Car& car) const {
car.running = true;
}
};
int main() {
Car car;
Engine engine;
car.status();
engine.start(car);
car.status();
}
Engine can access Car::running because Car declared Engine as a friend.
Friendship Rules
1. Not Mutual
If Car declares Engine as friend, Engine can access Car.
But Car does not automatically access private members of Engine.
2. Not Inherited
If a class is a friend, its child class is not automatically a friend.
3. Not Transitive
If A is friend of B, and B is friend of C, A is not automatically friend of C.
When To Use Friend Classes
Use rarely.
Reasonable examples:
- container and iterator
- tightly connected low-level helper class
- test helper in some designs
Do not use friend classes just to avoid writing a good public interface.
Viva Answer
A friend class is allowed to access private and protected members of another class. Friendship is not mutual, not inherited, and not transitive. It should be used rarely because it creates tight coupling.
Quick Check
- What is a friend class?
- Is friendship mutual?
- Is friendship inherited?
- Why can friend classes create tight coupling?