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 theMyClass
class. As a result, it can access the private memberprivateData
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 ofMyClass
, so it can access the private memberprivateData
.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.
I bought this course, it worth it!
Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it
Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website
Quick answers to common questions about our courses, quizzes, and learning platform
SCIAKU Team please upload 1st video of TREE please please please, please