🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to C++ Notes
Topic #93

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.

Want to go beyond the notes?

Join CodingNow 2.0's C++ course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

C++ Friend Functions – FAQs

Quick answers about learning C++ Friend Functions in C++.

This free note from CodingNow 2.0 explains C++ Friend Functions in C++ — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every C++ topic on CodingNow 2.0, including C++ Friend Functions, is 100% free with no signup required.
With focused practice, most students grasp C++ Friend Functions in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now