A friend function is a non-member function that is granted exceptional permission to access the private and protected data members of a class. While data hiding normally prevents outside code from tampering with a class's internal state, declaring a function as a friend breaks this rule safely under the class's explicit control.
Notes:
Let's modify our paddle class in our encapsulation lession to create a friend function that accesses the private variables (xPos and yPos) and displays them.
#include <iostream>
using namespace std;
class Paddle{
private:
int xPos;
int yPos;
int interval = 5;
public:
Paddle(int x, int y){
xPos = x;
yPos = y;
}
void moveUp(){
yPos = yPos + interval;
}
void moveDown(){
yPos = yPos - interval;
}
void setXPosition(int x){
xPos = x;
}
void setYPosition(int y){
yPos = y;
}
//Declare the friend function
friend void setPaddlePositions(Paddle &paddle,int x, int y);
friend void printBallPositions(Paddle paddle);
};
//Implement the friend function
void setPaddlePositions(Paddle &paddle,int x, int y){
paddle.xPos = x;
paddle.yPos = y;
}
void printBallPositions(Paddle paddle){
cout << "Paddle is at (" << paddle.xPos << "," << paddle.yPos << ")" << endl;
}
int main() {
Paddle paddle(5,50);
//Show the x and y coordinates of the paddle using the friend function
printBallPositions(paddle);
//The up arrow key pressed 5 times
paddle.moveUp();
paddle.moveUp();
paddle.moveUp();
paddle.moveUp();
paddle.moveUp();
printBallPositions(paddle);
//The down arrow pressed 2 times
paddle.moveDown();
paddle.moveDown();
printBallPositions(paddle);
//Set private values using set methods
paddle.setXPosition(50);
paddle.setYPosition(20);
printBallPositions(paddle);
//Assign values to the private variable using the friend function
setPaddlePositions(paddle,20, 80);
printBallPositions(paddle);
return 0;
}