Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

some friend functions don't follow the rule

Tags:

c++

friend

For the following snippet:

class A{
    friend void f(){};
    public:
        A(){f();} //error
};

class B{
    friend void f(void* ptr){};
    public:
        B(){f(this);} //no error
};

According to the rule that although friend functions can be defined inside a class, yet they are not visible until they are declared somewhere outside the class scope, the error in the definition of class A is explained.
But I am confused why the snippet for class B doesn't produce the same error as class A's.

Please can anyone tell me about this?

like image 365
Eddie Deng Avatar asked Feb 25 '15 14:02

Eddie Deng


People also ask

What are the limitations of friend function?

The major disadvantage of friend functions is that they require an extra line of code when you want dynamic binding. To get the effect of a virtual friend , the friend function should call a hidden (usually protected ) virtual member function. This is called the Virtual Friend Function Idiom.

Does friend function violates the concept of inheritance?

Limitations of friend function In C++, friendship is not inherited. If a base class has a friend function, then the function doesn't become a friend of the derived class(es).

Why are friend functions not preferred?

The most of OOP experts dislike friend function simply because they want the OOP part of C++ to behave like Smalltalk. But C++ is not Smalltalk, and they cannot even understand that friend don't break encapsulation, for the very simple reason that a function cannot be friend of your class without your class wants it.

Can friend function manipulate private members?

Yes, In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect friends. Friends are functions or classes declared with the friend keyword.


1 Answers

"Not visible" is a bit of an over-simplification. With only an in-class definition, a friend function can't be found by qualified or unqualified lookup, which is why the first snippet fails.

However, it can be found by argument-dependent lookup (ADL), so you can call it with an argument involving a type that's scoped in the same namespace as the function.

In this case, the argument type is B*, scoped in the global namespace. The friend function is scoped in the namespace containing the class that declares it - also the global namespace. So ADL will look in the global namespace for functions called f, find the friend function, and use that.

like image 113
Mike Seymour Avatar answered Sep 20 '22 16:09

Mike Seymour