Search code examples
c++classdeclarationprivate-membersfriend-function

How to befriend method from other class that handles this class (incomplete types problem)?


This sounds like a very obvious question but I can't find anything on the internet. I have a class other that handles a message in one of its methods. To do so, it has to access a private data member of the message, hence it should be friend of it. But I can't get it to compile. No matter the declaration order, it always complains about types being incomplete. How else would I accomplish such a thing?

Demo

#include <cstdio>

struct other;

class message
{
    friend auto other::handle_message(message) -> void;
    int private_ = 10;
};

struct other
{
    auto handle_message(message msg) -> void {
        printf("Private part of msg is %d!\n", msg.private_);
    }
};

int main() {}

Solution

  • What you need is the following

    class message;
    
    struct other
    {
        auto handle_message(message msg) -> void;
    };
    
    /* or just
        struct other
        {
            auto handle_message( class  message msg) -> void;
        };
    */
    
    
    class message
    {
        friend auto other::handle_message(message) -> void;
        int private_ = 10;
    };
    
    auto other::handle_message(message msg) -> void {
        printf("Private part of msg is %d!\n", msg.private_);
    }
    

    That is the class other must be defined before the class message and its member function handle_message must be defined after the definition of the class message.

    Here is a demonstration program.

    #include <cstdlib>
    
    class message;
    
    struct other
    {
        auto handle_message( message msg ) -> void;
    };
    
    class message
    {
        friend auto other::handle_message( message ) -> void;
        int private_ = 10;
    };
    
    auto other::handle_message( message msg ) -> void {
        std::printf( "Private part of msg is %d!\n", msg.private_ );
    }
    
    int main()
    {
        other().handle_message( message() );
    }
    

    The program output is

    Private part of msg is 10!