C++ Friend Function šŸŽÆ

beginner
25 min

C++ Friend Function šŸŽÆ

Welcome to our deep dive into C++ Friend Function! In this tutorial, we'll learn about this powerful feature of C++ that allows functions from one class to access the private and protected members of another class.

What is a Friend Function? šŸ“

A friend function is a non-member function that has access to the private and protected members of a class. Friend functions are declared within the class definition and are not members of the class. They are often used when it is necessary to perform operations that involve more than one class but cannot be performed using member functions alone.

Why use Friend Functions? šŸ’”

Friend functions are useful when you want to:

  1. Perform operations that involve more than one class but cannot be performed using member functions alone.
  2. Overcome the access specifier restrictions in C++, allowing a function defined outside the class to access the private members of the class.
  3. Improve the performance of certain operations by allowing functions to access private members directly.

Declaring a Friend Function šŸ“

To declare a friend function, use the friend keyword followed by the function declaration within the class definition. Here's a simple example:

cpp
#include <iostream> class MyClass { private: int myPrivateVariable; friend void printPrivate(MyClass); public: MyClass() { myPrivateVariable = 42; } void setPrivate(int value) { myPrivateVariable = value; } }; void printPrivate(MyClass obj) { std::cout << "Private variable: " << obj.myPrivateVariable << std::endl; } int main() { MyClass myObj; printPrivate(myObj); return 0; }

In this example, printPrivate is a friend function that can access the private member myPrivateVariable of MyClass.

Friend Class šŸ“

A friend class is similar to a friend function, but it grants all the member functions of a class access to the private and protected members of another class. To declare a friend class, use the friend keyword followed by the class name within the class definition of another class.

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What is a friend function in C++?

Stay tuned for more exciting lessons on C++ programming with CodeYourCraft! šŸŽ‰