Friendship

suggest change

The friend keyword is used to give other classes and functions access to private and protected members of the class, even through they are defined outside the class`s scope.

#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;
}
10
10, 5
Animal height: 5

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Classes / structs:
* Friendship

Table Of Contents
8 Arrays
11 Loops
19 Classes / structs
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype