Access Control and Friend Functions
Encapsulation restricts direct access to class internals and provides controlled access through public methods. C++ also has the friend keyword for granting access.
Example
class Temperature {
private:
double celsius;
public:
Temperature(double c) : celsius(c) {
if (c < -273.15) throw invalid_argument("Below absolute zero");
}
double getCelsius() const { return celsius; }
double getFahrenheit() const { return celsius * 9.0 / 5.0 + 32; }
double getKelvin() const { return celsius + 273.15; }
void setCelsius(double c) {
if (c < -273.15) throw invalid_argument("Below absolute zero");
celsius = c;
}
// Friend function can access private members
friend ostream& operator<<(ostream& os, const Temperature& t) {
os << t.celsius << "°C";
return os;
}
};
Temperature t(100);
cout << t << endl; // "100°C"
cout << t.getFahrenheit() << endl; // 212 