C++ Interview Questions
What is actual use of friend function and classes in C++?
If you declare a function is a friend of a class, then this function can visit private members in this class.
For example, it is a good idea of the <<
and >>
operator overloading and adding as a friend of those classes.
1 |
|
The friend
specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example, in the below code anyone may ask a child for their name, but only the mother and the child may change the name.
You can take this simple example further by considering a more complex class such as a window. Quite likely a window will have many function/data elements that should not be publicly accessible, but are needed by a related class such as a WindowManger.
1 | class Child { |
At work we use friends for testing code
, extensively. It means we can provide proper encapsulation and information hiding for the main application code. But also we can have separate test code that uses friends to inspect internal state and data for testing.
- Friend Definition
Friend definition allows to define a function in class-scope, but the function will not be defined as a member function, but as a free function of the enclosing namespace, and won’t be visible normally except for argument dependent lookup. That makes it especially useful for operator overloading:
1 | namespace utils { |
- Private CRTP Base Class
Sometimes, you find the need that a policy needs access to the derived class:
1 | // Possible policy used for flexible-class |
You will find a non-contrived example for that in this example. Another code
C++ Interview Questions
https://wtffqbpl.github.io/2023/05/13/C-Interview-Questions/