c++c++11program-entry-pointlanguage-lawyerfriend

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?

Solution

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