Namespaces
Variants
Views
Actions

friend specifier

From cppreference.com
< cpp‎ | language
Revision as of 12:50, 3 December 2012 by Bazzy (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function declaration
inline specifier
Exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
decltype (C++11)
auto (C++11)
alignas (C++11)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Implicit conversions - Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Classes
Access specifiers
friend specifier
Class-specific function properties
Special member functions
Templates
Miscellaneous
 

The friend keyword is used to grant access to private and protected class members from outside the class.

Contents

Syntax

friend Template:sparam

Description

The friend declaration happens inside a class declaration.

Template:sparam declares either a different class or an external function. The class or function declared here will have full access to the enclosing class internals. This is mostly used for external operators. Friendship is not inherited.

Friend declarations can happen in a block with any accessibility with no change.

Example

class MyClass {
private:
    int i;
 
 
    friend std::ostream& operator<<(std::ostream& out, const MyClass& o);
    friend std::istream& operator>>(std::istream& in, MyClass& o);
    friend swap(T& left, T& right);
    friend class YourClass;
};
 
// this function matches the friend declaration so it can access MyClass private members
std::ostream& operator<<(std::ostream& out, const MyClass& o)
{
    return out << o.i;
}



See Also

Class declaration
Access specifiers