Imaginary friends in C++

braindamage с++

Now I try to dig into C++ internals (TBH, at this moment I trying to remember C++). And I found funny thing with friend classes and functions in C++. Actually I must say thanks to a random mistake which help me to discovery it.

Let's see at this code:

#include <iostream>

class Foo {
    friend class Bar;

    void exec() {
        std::cout << "Exec foo object method" << std::endl; 

int main() {
    Foo foo;


    return 0;

This code is successfully compiles and runs.

When I see this I was literally surprised. Class Bar doesn't exists but class Foo declare it as his friend. What the hell? Or class Foo now has imaginary friend? It is the moment when I released that I don't know C++ :D Then I went to RTFM and get that in C++ friend class or function declaration doesn't affect to the class which declared it but affected class or function which declared as friend that class. Maybe this thing is so trivial but IMHO it so funny :)

Previous Post