bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/C++/C++ Classes
C++•C++ Classes

C++ The Friend Keyword

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

This chapter

Overview
17

Lessons

49m

Read time

1. C++ OOP2. C++ Classes and Objects3. C++ Class Methods4. C++ Constructors5. C++ Constructor Overloading6. C++ Access Specifiers7. C++ Encapsulation8. C++ The Friend Keyword9. C++ Inheritance10. C++ Multilevel Inheritance11. C++ Multiple Inheritance12. C++ Inheritance Access13. C++ Polymorphism14. C++ Virtual Functions15. C++ Templates16. C++ Files17. C++ Date and Time

On this page

C++ Friend FunctionsExample Explained