In a class, if the function is declared as friend within the different specifier like - private, protected, or public, then is there any difference. As per my understanding, friend function is not a member. Thus, it shouldn't matter. But, if I see static - it is also not a member, but access specifier matters a lot. So, I am a bit confused. How all these code works fine? Is there any difference among the following classes?
/** Private friend function **/
class frienddemoFunction
{
private:
unsigned int m_fanSpeed;
unsigned int m_dutyCycle;
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
public:
void setFanSpeed(unsigned int fanSpeed);
unsigned int getFanSpeed();
};
/** Protected -- Friend Function **/
class frienddemoFunction
{
private:
unsigned int m_fanSpeed;
unsigned int m_dutyCycle;
public:
void setFanSpeed(unsigned int fanSpeed);
unsigned int getFanSpeed();
protected:
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
};
class frienddemoFunction
{
private:
unsigned int m_fanSpeed;
unsigned int m_dutyCycle;
public:
void setFanSpeed(unsigned int fanSpeed);
unsigned int getFanSpeed();
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
};
/** This function is not a member of class frienddemo **/
friend void printValues(frienddemoFunction &d);
Normally, you can only access the private members of a class through member functions of that class, and you can only access the protected members of a class through member functions of a class or classes derived from that class. Friend declarations are not affected by access specifiers.
The Protected Friend keyword combination is a member access modifier. It confers both Friend access and Protected access on the declared elements, so they are accessible from anywhere in the same assembly, from their own class, and from derived classes.
A friend function is a function that isn't a member of a class but has access to the class's private and protected members. Friend functions aren't considered class members; they're normal external functions that are given special access privileges.
A friend function in C++ is defined as a function that can access private, protected and public members of a class.
No, it doesn't matter.
C++ standard, section § 11.3 / 9 [friend.class]
The meaning of the friend declaration is the same whether the friend declaration appears in the private, protected or public (9.2) portion of the class member-specification.
Note:
A static function declared within the class is still a class member. A friend function is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With