I know the friend
declaration
I've never used it before
I don't know when to use it.
If you think about the encapsulation of OOP,
Isn't friend
an exceptional function?
Specifying friend
enables the class to access protect data/function
.
Anyone can access the name
of the Child
class from the code below
Only the Mother
class can replace the name
of the Child
class.
class Child
{
friend class Mother;
public:
string name (void); //all accessible
protected:
void setName (string newName); //Mother is accessible
};
It's hard to understand in this simple example, If you think about the case where there are many complex classes like Windows,
WindowManager
and Window
are not inheritance relationships,
WindowManager
must have access to function/data that should not be accessed publicly in Window
.
In this situation, friend
is useful.
© 2024 OneMinuteCode. All rights reserved.