-3

Can main function become friend function in C++ ?

 #include "stdafx.h"
#include <iostream>
using namespace std;
class A {
public:
    A():i(10){}
private:
    int i;
    friend int main();
};

int main()
{
    A obj;
    cout<<obj.i;
    return 0;
}
Rohit
  • 6,941
  • 17
  • 58
  • 102
  • 1
    OK, now what's the question? Language syntax? – Adriano Repetti Jun 11 '13 at 16:14
  • how does it work? friend allows the function int main() to access the private variables and functions of class A. A's constructer sets i to 10 int main() access i (as it is a "friend" and can access the private variable i) and couts it. – Daboyzuk Jun 11 '13 at 16:16

2 Answers2

5

3.6.1 of the Standard (wording from draft n3936, but it's the same in C++03) says that:

The function main shall not be used within a program.

The exact meaning of this rule isn't clear. The Standard formally defines semantics for the related term odr-used, but not simply used.

To be safe, assume that this rule means that "The function main shall not be named in a friend declaration."


Interestingly, although the wording of this rule is identical to C++03, in that version what we now know as odr-used hadn't yet been renamed, and this rule was clearly referring to that concept. I wonder whether this was overlooked during the rename from used to odr-used. If the new term was intentionally not used here, the rationale for that decision might illuminate what uses, exactly, are intended to be forbidden.


Shafik found that the rename took place in N3214, and this rule was intentionally not changed to odr-use, although it doesn't explain why.

Community
  • 1
  • 1
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • A `friend` declaration does not odr-use the identifier though – M.M Aug 15 '14 at 03:03
  • @MattMcNabb: Right, but the Standard language forbids all use, not just odr-use. – Ben Voigt Aug 15 '14 at 11:58
  • OK, I thought you were speculating that it might be a defect and they meant to change it to *odr-used* along with everything else. – M.M Aug 15 '14 at 12:02
  • @MattMcNabb: Ok. Yes I am speculating that. The rule used to mean *odr-used*, which went under the name *used*, and it no longer does. Without clarification. I would love to know whether this rule was discussed in the proposal that changed *used* to *odr-used*. – Ben Voigt Aug 15 '14 at 12:28
4

Can main function become friend function in C++ ?

Yes, it can.

The friend declaration in your class A grants function main() the right of accessing the name of its non-public data members (in this case, i):

friend int main();

The object obj is default-constructed, and A's constructor sets the value of i to 10:

A() : i(10) {}
//  ^^^^^^^
//  Initializes i to 10 during construction

Then, the value obj.i is inserted into the standard output:

cout << obj.i;
//      ^^^^^
//      Would result in a compiler error without the friend declaration
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451