Please see my first attempt at answering this . I neglected to tell the whole story before in an attempt to simplify things. Turns out my example works! Sorry.
The whole story is that this is a library the contains a class in one file and the main in another file, all linked into my library. The library is providing the basis for a Process Framework, which is why the main is in the library and not the process.
Below is a stripped down version of what I have.
pf.hpp
using namespace std;
namespace MyNamespace
{
class ProcessManager
{
public:
friend int main(int argc, char** argv);
private:
void test();
};
};
pf.cpp
#include "pf.h"
namespace MyNamespace
{
ProcessManager::test()
{
cout << "My friend has accessed my member" << endl;
}
};
pfmain.cpp
#include "pf.hpp"
int main(int argc, char** argv)
{
ProcessManager pm;
pm.test();
}
Note that this fails on the compilation of the library
What I have tried is:
What am I missing?
Thanks!
A function or class can't declare itself as a friend of any class. In a class definition, use the friend keyword and the name of a non-member function or other class to grant it access to the private and protected members of your class. In a template definition, a type parameter can be declared as a 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.
A friend function is a non member function or ordinary function of a class, which is declared as a friend using the keyword “friend” inside the class. By declaring a function as a friend, all the access permissions are given to the function.
According to the C++ Primer book, the author mentioned that we can specify a class member function as a friend of another class, instead of the entire class (page 634).
Just declare the main outside the MyNamespace
and specify global namespace ::
in friend statement
//in header file of ProcessManager
//your pf.h
int main(int argc, char** argv);
namespace MyNamespace
{
class ProcessManager
{
public:
friend int ::main(int argc, char** argv);
private:
void test();
};
};
@parapura provided a solution, but doesn't explain why you first have to declare main
in the global scope.
§7.3.1.2 [namespace.memdef] p3
[...] If a
friend
declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. [...]
So with that in mind, your code would look somewhat like this:
namespace MyNamespace
{ // MyNamespace is the innermost enclosing namespace
// 'main' from the friend declaration is treated
// as if it was a member of 'MyNamespace'
int main(int argc, char** argv);
class ProcessManager
{
public:
friend int main(int argc, char** argv);
private:
void test();
};
};
Now it should be clear why the global main
function wasn't your friend.
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