Classes / structs / Friendship / Essential C++

Run Settings
LanguageC++
Language Version
Run Command
#include <iostream> class Animal { private: double weight; double height; public: Animal(double w, double h) : weight(w), height(h) { } friend void printWeight(Animal animal); friend class AnimalPrinter; // A common use for a friend function is to overload the operator<< for streaming. friend std::ostream& operator<<(std::ostream& os, Animal animal); }; void printWeight(Animal animal) { std::cout << animal.weight << "\n"; } class AnimalPrinter { public: void print(const Animal& animal) { // Because of the `friend class AnimalPrinter;" declaration, we are // allowed to access private members here. std::cout << animal.weight << ", " << animal.height << std::endl; } }; std::ostream& operator<<(std::ostream& os, Animal animal) { os << "Animal height: " << animal.height << "\n"; return os; } int main() { Animal animal = {10, 5}; printWeight(animal); AnimalPrinter aPrinter; aPrinter.print(animal); std::cout << animal; }
Editor Settings
Theme
Key bindings
Full width
Lines