C++ Friend Class šŸŽÆ

beginner
24 min

C++ Friend Class šŸŽÆ

Welcome to our comprehensive guide on the C++ Friend Class! In this lesson, we'll delve into the intricacies of the friend class in C++, a powerful feature that allows you to grant special access rights to other classes or functions. Let's get started! šŸ“

Understanding Friend Class šŸ’”

In C++, the friend keyword is used to declare a function or a class as a friend of another class. This means that the friend class or function has direct access to the private and protected members of the class it is declared as a friend of.

Here's a simple analogy: Imagine you have a secret club (a class) with a special password (private member). Now, your best friend (friend class) knows the password and has full access to the club's inner workings, just like a friend function or class in C++.

Declaring a Friend Function šŸ’”

You can declare a friend function in the class definition itself. Here's an example:

cpp
class MyClass { private: int secretNumber; friend void showSecret(MyClass); }; void showSecret(MyClass obj) { std::cout << "The secret number is: " << obj.secretNumber << std::endl; }

In the above example, showSecret is a friend function of MyClass. It has direct access to the private member secretNumber of MyClass.

Declaring a Friend Class šŸ’”

Declaring a friend class is similar to declaring a friend function. Here's an example:

cpp
class MyClass { private: int secretNumber; friend class MyFriendClass; }; class MyFriendClass { public: void printSecret(MyClass obj) { std::cout << "The secret number is: " << obj.secretNumber << std::endl; } };

In the above example, MyFriendClass is a friend of MyClass. It has direct access to the private member secretNumber of MyClass.

Friend Class and Inheritance šŸ’”

When a base class declares a friend class, the friend class also gains access to the private and protected members of the derived classes. Here's an example:

cpp
class Base { private: int secretNumber; friend class Derived; }; class Derived : public Base { public: void printSecret(Base obj) { std::cout << "The secret number is: " << obj.secretNumber << std::endl; } };

In the above example, Derived is a friend of Base. It has direct access to the private member secretNumber of Base.

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What is the purpose of the friend keyword in C++?

That's all for today's lesson! In the next lesson, we'll dive deeper into the world of friend classes, exploring more complex examples and best practices. Stay tuned! šŸ’”