Martin's Tex-Blog

Posts on programming and generally technical topics

Friend definition – or friend functions defined inside class body

leave a comment »

This is a slightly less known feature of C++ which allows you to define a function that can be called only by using Argument Dependent Lookup (ADL). Compiler will create non-member function in the namespace surrounding class where it is defined. This is how it looks like:

namespace Forest {
class CTree {
CTree(int) {}

// This parameter less foo function is actually unaccessible
friend void foo() {}

// This one is accessibly only through ADL
friend void foo(const CTree&) {}

Forest::CTree tree(0);
foo(tree); // ok - call by ADT
//foo(); // error
//foo(0); // error - foo is not considered as candidate using ADL due to required implicit conversion
//Forest:foo(); // error
//Forest::foo(tree); // error
//Forest::foo(); // error

So, how is that usefull to us? It allows you to call a foo function without qualifying it with namespace name. It makes greater sense in case of operator definitions. If you define operator== as a friend inside class body, then it will get called only by ADL – as it should, and it will also have full access to your class private data. Coders mostly define binary operators as a free function to allow for implicit conversions of arguments. The problem with friend defined operator is that implicit conversion will not happen.



Written by Marcin

January 11, 2015 at 1:08 am

Posted in C++

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: