When do you use friend in class?

Asked 2 years ago, Updated 2 years ago, 125 views

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?

oop c++ encapsulation friend

2022-09-22 08:17

1 Answers

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.


2022-09-22 08:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.