Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access friend function defined in class

Tags:

c++

friend

There is such code:

#include <iostream>  class A{  public:     friend void fun(A a){std::cout << "Im here" << std::endl;}     friend void fun2(){ std::cout << "Im here2" << std::endl; }     friend void fun3(); };  void fun3(){     std::cout << "Im here3" << std::endl; }  int main()  {       fun(A()); // works ok     //fun2(); error: 'fun2' was not declared in this scope     //A::fun2(); error: 'fun2' is not a member of 'A'     fun3(); // works ok }  

How to access function fun2()?

like image 537
scdmb Avatar asked Oct 16 '11 17:10

scdmb


People also ask

How do you access a friend's class function?

Syntax of friend functions: class className{ // Other Declarations friend returnType functionName(arg list); }; As we can see above, the friend function should be declared inside the class whose private and protected members are to be accessed.

Where friend function is defined?

A friend function in C++ is defined as a function that can access private, protected and public members of a class. The friend function is declared using the friend keyword inside the body of the class.


1 Answers

class A{  public:     friend void fun(A a){std::cout << "Im here" << std::endl;}     friend void fun2(){ std::cout << "Im here2" << std::endl; }     friend void fun3(); }; 

Although your definition of fun2 does define a "global" function rather than a member, and makes it a friend of A at the same time, you are still missing a declaration of the same function in the global scope itself.

That means that no code in that scope has any idea that fun2 exists.

The same problem occurs for fun, except that Argument-Dependent Lookup can take over and find the function, because there is an argument of type A.

I recommend instead defining your functions in the usual manner:

class A {    friend void fun(A a);    friend void fun2();    friend void fun3(); };  void fun(A a) { std::cout << "I'm here"  << std::endl; } void fun2()   { std::cout << "I'm here2" << std::endl; } void fun3(); 

Notice now that everything works (except fun3 because I never defined it).

like image 88
Lightness Races in Orbit Avatar answered Sep 20 '22 03:09

Lightness Races in Orbit