[Solved] C++: friend as main in class


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

solved C++: friend as main in class