Hi all,

This is my first post here.

Basically I want to use friend classes across namespace. eg:

#include <iostream>

namespace NamespaceA {

    class ClassA {
    public:
        friend class ClassB;
        void print( ) {
            std::cout<<std::endl<<data<<std::endl;
        }
    private:
        int data;
    };
};

namespace NamespaceB {
    class ClassB {
    public:
        ClassB() {
            NamespaceA::ClassA obj;
            obj.data = 10;
            obj.print();
        }
    };
};

int main(int argc, char *argv[])
{
    NamespaceB::ClassB obj;

    return 0;
}

When I compile this, I get following error,

main.cpp: In constructor `NamespaceB::ClassB::ClassB()':
main.cpp:12: error: `int NamespaceA::ClassA::data' is private
main.cpp:21: error: within this context

How to fix this error?

FYI, some body has written about this in
http://stupefydeveloper.blogspot.com/2008/04/c-friend-classes-in-namespaces.html

But I didn't understand the solution.

Found the solution my self,

#include <iostream>

namespace NamespaceB {
    class ClassB;
};

namespace NamespaceA {

    class ClassA {
    public:
        friend class NamespaceB::ClassB;
        void print() {
            std::cout<<std::endl<<data<<std::endl;
        }
    private:
        int data;
    };
};

namespace NamespaceB {
    class ClassB {
    public:
        ClassB() {
            NamespaceA::ClassA obj;
            obj.data = 10;
            obj.print();
        }
    };
};

int main(int argc, char *argv[])
{
    NamespaceB::ClassB obj;

    return 0;
}

shall fix it.

This question has already been answered. Start a new discussion instead.