1
votes

I'm trying to access the private data members of a struct from a friend class as shown below. All the code is in a single cpp file:

namespace Foo
{
    struct TestStruct
    {
        friend class Bar;

        private:

            int _testNum;
    };
}

class Bar
{
    public:

        Bar();

    private:

        Foo::TestStruct _testStructObj;
};

Bar::Bar()
{
    _testStructObj._testNum = 10; //Cannot modify _testNum because it is private
}

On compilation, I get an error saying that _testNum in the struct TestStruct is private hence inaccessible. After trying different things and searching the web I finally decided to remove the namespace and the code compiles. Why can't I access the private data members of the struct from a friend class when the struct is defined in a namespace?

1
Beware leading underscores on names; they're mostly reserved for the implementation to use — so you shouldn't use them.Jonathan Leffler

1 Answers

3
votes

When saying friend class Bar;, it's still inside the Foo namespace, but your class Bar is outside. Use the unary scope resolution operator to specify that Bar is in the global namespace instead of in Foo:

friend class ::Bar;

You'll also have to either forward declare or define Bar before TestStruct:

class Bar;

namespace Foo {
    ...
}

class Bar {
    ...
};