Friend Keyword In C++

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 131:- Friend Keyword In C++

In C++, the friend keyword is used to grant access to private or protected members of a class to functions or other classes that are not part of the class itself. This allows external entities to access private or protected members, breaking the encapsulation principle, but it can be useful in specific scenarios.

When a function or class is declared as a friend of another class, it can access the private and protected members of that class as if they were its own members.

Here's how the friend keyword is used:

 

cppCopy code

class MyClass { private: int privateData; public: MyClass(int data) : privateData(data) {} friend void friendFunction(MyClass &obj); }; void friendFunction(MyClass &obj) { // Friend function can access private member std::cout << "Friend Function: " << obj.privateData << std::endl; } int main() { MyClass myObj(42); friendFunction(myObj); return 0; }

In this example, friendFunction is declared as a friend of the MyClass class. As a result, it can access the private member privateData of the class.

The friend keyword can also be used to declare entire classes as friends:

 

cppCopy code

class AnotherClass { public: void accessPrivateData(MyClass &obj) { std::cout << "AnotherClass: " << obj.privateData << std::endl; } }; class MyClass { private: int privateData; friend class AnotherClass; // Declare AnotherClass as a friend public: MyClass(int data) : privateData(data) {} }; int main() { MyClass myObj(42); AnotherClass anotherObj; anotherObj.accessPrivateData(myObj); return 0; }

Here, AnotherClass is declared as a friend of MyClass, so it can access the private member privateData.

It's important to use the friend keyword judiciously, as it can potentially break encapsulation and make your code less maintainable. In many cases, there are alternative approaches to achieve the desired functionality without relying on friend classes or functions.

17. OOPs

2 Comments

@mk.info.work
mk.info.work Feb 17, 2024 at 10:20 PM

SCIAKU Team please upload 1st video of TREE please please please, please

@na3744
na3744 Feb 23, 2024 at 2:52 AM

I bought this course, it worth it!

@mk.info.work
mk.info.work Nov 15, 2023 at 10:25 PM

Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it

@sciaku1
sciaku1 Jan 11, 2024 at 3:23 PM

Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support