Argument-Dependent Lookup and the Hidden Friend Idiom

Contents[Show]

Argument-Dependent Lookup (ADL), also known as Koenig Lookup, is a set of "magical" rules for the lookup of unqualified functions based on their function arguments.

GeneralIdioms

 

The Hidden Friend Idiom is based on Argument-Dependent Lookup (ADL). Therefore, let's start this post with ADL.

Argument-Dependent Lookup

Have you ever wondered why the following program works?

#include <iostream>

int main() {
    std::cout << "Hello world";
}

 

Why should the program not work? The overloaded output operator operator<< is defined in the std namespace. The question is, therefore: How is the appropriate overloaded output operator for std::string found? You may already assume it.

Wikipedia has a nice definition of ADL:

  • Argument-Dependent Lookup: In the C++ programming language, argument-dependent lookup (ADL), or argument-dependent name lookup, applies to the lookup of an unqualified function name depending on the types of the arguments given to the function call. This behavior is also known as Koenig lookup, as it is often attributed to Andrew Koenig, though he is not its inventor.(https://en.wikipedia.org/wiki/Argument-dependent_name_lookup)

Let's analyze this. Here is a simple example of applying ADL:

// adl.cpp

namespace MyNamespace {
    struct MyStruct {};
    void function(MyStruct) {}
}   

int main() {

    MyNamespace::MyStruct obj;  
    function(obj);     // (1)

}

 

The call function(obj) in line (1) would fail without Argument-Dependent Lookup. Thanks to ADL, the lookup for unqualified function names includes the namespace of their arguments in addition to the usual unqualified name lookup. Consequentially, the name function is found in the namespace MyNamespace.

Now, we know what ADL means. But this does not solve our original challenge. Why does the simple "Hello World" program work?

#include <iostream>

int main() {
    std::cout << "Hello world";
}

 

Let's try it out with C++ Insights:https://cppinsights.io/s/bfb25e37

#include <iostream>

int main()
{
  std::operator<<(std::cout, "Hello world");  // (1)
  return 0;
}

 

The call  std::cout << "Hello world"; is equivalent to the function call operator<<(std::cout, "Hello world"); (line 1). ADL regards the namespace of its arguments that includes in our concrete case std::cout.

Finally, let me write about the Hidden Friend Idiom.

 

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs. Subscribe for the news.

 

 

Hidden Friend Idiom

Argument-Dependend Lookup extends the public interface of a class: non-member functions or non-member operators extend the public interface of that class. Now, the Hidden Friend Idiom kicks in:

Friend functions or operators defined inside the class have two special properties:

  1. They can access the private members of the class.
  2. They are non-member functions or operators.

The second point is pretty unknown, and I regularly have to explain it when I give a class.  A friend function defined inside the class has interesting consequences for the overloading of operators. Friend operators defined inside the class can access the private members of the class, are non-member functions, and are found by Argument-Dependent Lookup.

 

// hiddenFriend.cpp

#include <iostream>

class MyDistance{
 public:
    explicit MyDistance(double i):m(i){}

    friend MyDistance operator +(const MyDistance& a, const MyDistance& b){         // (1)
        return MyDistance(a.m + b.m);
    }
    
    friend MyDistance operator -(const MyDistance& a, const MyDistance& b){         // (2)
        return MyDistance(a.m - b.m);
    }

    friend std::ostream& operator<< (std::ostream &out, const MyDistance& myDist){  // (3)
        out << myDist.m << " m";
        return out;
    }
    
 private:
    double m;

};


int main() {

    std::cout << '\n';

    std::cout << "MyDistance(5.5) + MyDistance(5.5): " << MyDistance(5.5) + MyDistance(5.5) << '\n';  // (4)

    std::cout << "MyDistance(5.5) - MyDistance(5.5): " << MyDistance(5.5) - MyDistance(5.5) << '\n';  // (5)

    std::cout << '\n';

}

 

All three operators in lines (1), (2), and (3) are friends. The corresponding operators (+) in line (4) and (-) in line (5) are found as expected.

C++ Insights shows once more the magic of operator overloading: https://cppinsights.io/s/50aae5ed

In particular, the addition in line (4) (MyDistance(5.5) + MyDistance(5.5)) is transformed into: operator+(MyDistance(5.5), MyDistance(5.5)).

Finally, here is the output of the program:

hiddenFriend

On the contrary, let me remove the friend declaration from the overloaded+ operator.

 

class MyDistance{
 public:
    explicit MyDistance(double i):m(i){}

    MyDistance operator +(const MyDistance& a, const MyDistance& b){        
        return MyDistance(a.m + b.m);
    }
    
    friend MyDistance operator -(const MyDistance& a, const MyDistance& b){      
        return MyDistance(a.m - b.m);
    }

    friend std::ostream& operator<< (std::ostream &out, const MyDistance& myDist){ 
        out << myDist.m << " m";
        return out;
    }
    
 private:
    double m;

};

 

Now, the compilation fails:

hiddenFriendBroken

 

The compiler essentially complains in the first line that the definition of the operator+ can only have zero or one argument (hiddenFriend:9:16). Without the friend declaration, the operator+ is a member function, and as such, it has an implicit this pointer. This means that the operator+ has in sum three arguments. That is not valid c++. Consequentially, the compiler does not find the appropriate operator+ (hiddenFriend:32:75).

What's Next?

In addition to the Hidden Friend Idiom, C++ has many more idioms for class design. In my next post, I will write about the Rule of Zero, Five, or Six.

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, and Ben Atakora.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, Mipko, and Alicja Kaminska.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

Comments   

0 #1 Luan Young 2023-02-04 14:30
Thank you for one more great post! I think it would be interesting the discussion and I would like to know the pros and cons between the hidden friend idiom, the definition of operators overloading as members functions (with the right parameters of course) and as free functions in the same namespace as the class definition. Best regards!
Quote

Mentoring

Stay Informed about my Mentoring

 

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 349

Yesterday 7363

Week 15709

Month 47785

All 11343199

Currently are 144 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments