bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/C++/C++ Classes
C++•C++ Classes

C++ The Friend Keyword

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind C++ The Friend Keyword?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ Employee {
3Order

Put the learning moves in the order that makes the concept easiest to apply.

A friend function is not a member of the class, but it is allowed to access the class's private data:
Normally, private members of a class can only be accessed using public methods like getters and setters .
C++ Friend Functions

C++ Friend Functions

Normally, private members of a class can only be accessed using public methods like getters and setters . But in some cases, you can use a special function called a friend function to access them directly.

A friend function is not a member of the class, but it is allowed to access the class's private data:

Example

class Employee {
  private: int salary;
  public: Employee(int s) {
    salary = s;
  }
// Declare friend function friend void displaySalary(Employee emp);
};
void displaySalary(Employee emp) {
  cout << "Salary: " << emp.salary;
}
int main() {
  Employee myEmp(50000);
  displaySalary(myEmp);
  return 0;
}

Example Explained

  • The friend function displaySalary() is declared inside the Employee class but defined outside of it.
  • Even though displaySalary() is not a member of the class, it can still access the private member salary .
  • In the main() function, we create an Employee object and call the friend function to print its salary.

Previous

C++ Encapsulation

Next

C++ Inheritance