Friend deep meaning
Friend Deep Meaning :
.
a person that you know and like (not a member of your family), and who likes you
मित्र, दोस्त (जो परिवार का सदस्य नहीं है)
"in applicable in c++ also your question rise in how can : let be explain it we know C++ are object oriented program it deals with class and objects , class inside define a function is known as member function and which function define in other class and its another class is knows as friend function
LETS IN PROGRAM IN FRIEND MEANING
In the context of C++ programming, the keyword
friend
is used to declare a function or a class as a friend of another class. This concept is related to access control in object-oriented programming and allows the declared friend to access the private and protected members of the class it is declared as a friend of.Here's how it works:
- Friend Function: A friend function is a non-member function that is granted access to the private and protected members of a class. It is declared inside the class but defined outside of it. Friend functions are often used when you need to perform operations on private members of a class without making those members public
- class MyClass { private: int data; public: MyClass(int value) : data(value) {} friend void friendFunction(MyClass& obj); // Declaration of a friend function }; void friendFunction(MyClass& obj) { // Friend function can access private members of MyClass std::cout << "Data from friendFunction: " << obj.data << std::endl; } int main() { MyClass myObj(42); friendFunction(myObj); // Calling the friend function return 0; }
Friend Class:
A friend class is a class that is granted access to the private and protected members of another class. This allows the friend class to manipulate and access the internals of the class it is a friend of.
class FriendClass {
public:
void accessData(MyClass& obj) {
// Friend class can access private members of MyClass
std::cout << "Data from FriendClass: " << obj.data << std::endl;
}
};
class MyClass {
private:
int data;
public:
MyClass(int value) : data(value) {}
friend class FriendClass; // Declaration of a friend class
};
int main() {
MyClass myObj(42);
FriendClass friendObj;
friendObj.accessData(myObj); // Calling the method of the friend class
return 0;
}
It's important to use the friend
keyword judiciously, as it breaks encapsulation to some extent by allowing external functions or classes access to private members. While it can be useful in certain situations, overuse of friend declarations can lead to less maintainable and more tightly coupled code.
In summary, in C++, the friend
keyword is used to grant access to private and protected members of a class to specific functions or classes, enhancing flexibility in design and implementation
Comments
Post a Comment