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
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
friend specifier
initializer lists
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

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