Search code examples
c++oopfriend

C++ Useless Friend Function Declaration


Well, I declared a friend function which is in:

// user-proc.h
class cregister{
 private:
  levy user; // typedef struct
  int testp;
 public:
  friend void test();
  cregister(levy &tmp);
  levy getUser();
  void displayUser(levy &);
};

Then I defined it in:

// user-proc.cpp
void test()
{
    cout << "test" << endl;
}

And I'm trying to call in main function but it gives me It wasn't declared in this scope. I did some research but what I find is, they saying friend type is not exactly declaration you have to define it out of class also. I tried it then normally error gone but as it happens friend functions cannot access private members.

EDIT : I used void test(); before class-definition and used object to access private members. It fixed that way.


Solution

  • It looks like there are two test() functions declared here; one in the class and one (with definition) in the cpp file.

    The test() that is only declared in the class is effectively only accessible via ADL and this won't work here since it takes no arguments of the type of the class.

    Add a declaration of void test(); before the class definition should make the internals of the class available in the test function.

    // user-proc.h
    
    void test();
    
    class cregister{
     // redacted...
     public:
      friend void test();
    };
    

    Whilst test() has access to the private members here, unless it declares an instance of the class (a valid object) to work with, the function is not too useful. Consider adding an argument for the function, something such as void test(cregister& arg); (and here ADL would kick in). I infer that the function here is specifically for testing, so the above may not apply, but in the general case it could be useful.