Home > Backend Development > C++ > How Does the Scope and Accessibility of Inline Friend Functions Work in C ?

How Does the Scope and Accessibility of Inline Friend Functions Work in C ?

DDD
Release: 2024-12-16 20:44:10
Original
438 people have browsed it

How Does the Scope and Accessibility of Inline Friend Functions Work in C  ?

Inline Friend Functions: Scope and Accessibility

When defining an inline friend function in a class, its scope is primarily influenced by the nearest enclosing namespace. The friend declaration introduces a function name into the namespace, but it does not immediately make the function visible for regular lookup within that scope.

According to the C standard (ISO/IEC 14882:2011), "if a friend declaration in a non-local class first declares a class or function, the friend class or function is a member of the innermost enclosing namespace." This means that the name of the friend function is initially not found through unqualified or qualified lookup within the namespace scope.

Only when a matching declaration is provided in the namespace scope itself, either before or after the class definition that grants friendship, will the function become visible through unqualified lookup. Additionally, the friend function can still be called through argument-dependent lookup, which considers functions from namespaces and classes associated with the argument types.

For example, the code provided in the question defines an inline friend function named baz in the bar class within the foo namespace. However, attempts to call baz from different scopes within the program result in errors because the function is not visible through regular lookup:

  • foo::baz() fails because baz is not a member of the foo namespace.
  • foo::bar::baz() fails because baz is not a member of the bar class.
  • foo::bar::call_friend() fails because baz was not declared within the scope of the call_friend member function.

Therefore, inline friend functions have limited accessibility and scope. They are primarily known for their ability to access private and protected members of a class without specifying the class name as a qualifier. However, their visibility within the surrounding scope is restricted until a matching declaration is provided in the namespace or through argument-dependent lookup.

The above is the detailed content of How Does the Scope and Accessibility of Inline Friend Functions Work in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template