I know that main
can be a friend of a class
:
#include <iostream>
class foo {
friend int main();
int i = 4;
};
int main() {
foo obj;
std::cout << obj.i << std::endl;
}
LIVE DEMO
However, I feel that although this is perfectably allowable it conceals many dangers.
main
a friend of a class?main
as friend of a class should be considered harmful? main() can very well be a friend of any class. Just declare it as a friend inside the class like you do for other member functions.
1) Friends should be used only for limited purpose. too many functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented programming. 2) Friendship is not mutual.
A friend function in the class declaration doesn't violate encapsulation any more than a public member function violates encapsulation: both have exactly the same authority with respect to accessing the class's non-public parts.)
When should you use 'friend' in C++? A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.
The choice whether to use or avoid a legal feature becomes moot if the feature is not, in fact, legal. I believe there's serious doubt surrounding this, because the Standard says
The function
main
shall not be used within a program.
There's already a question regarding whether befriending ::main()
is in fact allowed, and you'll find more details in my answer there.
The general frienship considerations should be identical as for any other functions.
However I see one possible danger:
C++ Standard :
A function first declared in a friend declaration has external linkage
The linkage of main is implementation-defined
So if your implementation expects main()
not to have external linkage and you first declare main()
as a friend (as in your example), you contradict the standard.
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