Quick actions

cmd+k|ctrl+k

Navigation

Languages

Classes / structs / Friendship / Essential C++

Snippet info

Language

Cpp

Visibility

public

Author

kkowalczyk

Created

2019-03-27T06:54:28Z

Updated

2019-03-27T06:54:28Z

#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;
}
INFO