example1_friend_function.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

class Box {
private:
    double width;
    double height;
    double depth;

public:
    Box(double w, double h, double d) : width(w), height(h), depth(d) {}

    // Declaration of friend function
    friend double calculateVolume(const Box& box);
};

// Definition of friend function
double calculateVolume(const Box& box) {
    return box.width * box.height * box.depth;
}

int main() {
    Box myBox(3.0, 4.0, 5.0);
    std::cout << "Volume of myBox: " << calculateVolume(myBox) << std::endl;
    return 0;
}
Back to friend