Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class friend function inside a namespace

Im trying to define a class friend function outside the namespace like this:

namespace A{
class window{
    private:
    int a;
    friend void f(window);
};
}

 void f(A::window rhs){
 cout << rhs.a << endl;
}

Im getting an error said that there is ambiguity. and there is two candidates void A::f(A::window); and void f(A::window). So my question is :

1) How to make the global function void f(A::window rhs) a friend of the class A::window.

EDIT: (After reading the answers)

2) why do I need to qualify the member function f inside window class to be global by doing ::f(window) ?

3) why do I need to predeclare the function f(A::window) in this particular case, whereas when the class is not a defined inside a namespace it's okey for the function to be declared after the function is declared a friend.

like image 336
AlexDan Avatar asked Jun 07 '12 14:06

AlexDan


People also ask

Can we define friend function inside the class?

Friend functions can be defined (given a function body) inside class declarations. These functions are inline functions. Like member inline functions, they behave as though they were defined immediately after all class members have been seen, but before the class scope is closed (at the end of the class declaration).

Can a class inherit friend function?

No. You cannot inherited friend function in C++. It is strictly one-one relationship between two classes. Friendship is neither inherited nor transitive.

Can two classes have same friend function?

A friend function can be friendly to 2 or more classes. The friend function does not belong to any class, so it can be used to access private data of two or more classes as in the following example. The friend functions can serve, for example, to conduct operations between two different classes.

Can we declare friend function outside the class?

The friend function can be a member of another class or a function that is outside the scope of the class. A friend function can be declared in the private or public part of a class without changing its meaning.


1 Answers

As well as adding a :: you need to forward declare it, e.g.:

namespace A { class window; }

void f(A::window);

namespace A{
  class window{
    private:
    int a;
    friend void ::f(window);
  };
}

void f(A::window rhs){
  std::cout << rhs.a << std::endl;
}

Note that for this forward declaration to work you need to forward declare the class too!

like image 171
Flexo Avatar answered Sep 24 '22 07:09

Flexo