Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring main as friend considered harmful?

Discussion

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.

Questions

  1. Are there any valuable uses in making main a friend of a class?
  2. Are there any reasons that declaring main as friend of a class should be considered harmful?
like image 466
101010 Avatar asked Jul 31 '14 22:07

101010


People also ask

Can we declare main function as friend?

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.

Why friend function should be avoided?

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.

Do friends violate encapsulation?

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.)

Should I use friend C++?

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.


2 Answers

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.

like image 118
Ben Voigt Avatar answered Oct 31 '22 00:10

Ben Voigt


The general frienship considerations should be identical as for any other functions.


However I see one possible danger:

C++ Standard :

  • Section § 11.3 (Friends)

A function first declared in a friend declaration has external linkage

  • Section § 3.6.1 (Main Function)

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.

like image 39
quantdev Avatar answered Oct 31 '22 00:10

quantdev