Friend Function
#include <iostream>
class Box {
private:
int width, height, depth;
public:
Box(int w, int h, int d) : width(w), height(h), depth(d) {}
// Declaration of friend function
friend int getBoxVolume(const Box& b);
// Friend function can be a member of another class
friend class BoxPrinter;
};
// Definition of friend function
int getBoxVolume(const Box& b) {
// Can access private members of Box
return b.width * b.height * b.depth;
}
class BoxPrinter {
public:
void printBoxDimensions(const Box& b) {
// Can access private members of Box
std::cout << "Width: " << b.width
<< ", Height: " << b.height
<< ", Depth: " << b.depth << std::endl;
}
};
int main() {
Box myBox(3, 4, 5);
std::cout << "Volume: " << getBoxVolume(myBox) << std::endl;
BoxPrinter printer;
printer.printBoxDimensions(myBox);
return 0;
}Last updated