0

classA.h:

#pragma once
#include "classC.h"

using namespace Bname;

namespace Aname
{
    class  A
    {
        friend class B;
    private:
        void Aclassmethod();
    };

}

classB.h:

#pragma once
namespace Bname
{
    class B
    {
    public:
        void Bclassmethod();
    };
}

classC.h:

#pragma once
namespace Bname
{
    class C
    {
    };
}

classA.cpp:

#include "classA.h"

void Aname::A::Aclassmethod()
{
}

classB.cpp

#include "classB.h"
#include "classA.h"

void Bname::B::Bclassmethod()
{
    Aname::A *vv = new Aname::A();
    vv->Aclassmethod();            **ERROR**// Aclassmethod is a private member of Aname::A
}

I try to compile the code for macos as dynamic library ,The code is Getting compiler error in Xcode cpp (Accessing private Member of class),But Its Properly Compiling without any error in Visual studio.

fiaazmd
  • 13
  • 2
  • On a side note `using namespace Bname;` don't. You pull the whole namspace B into the global namespace. Rather add `using B::B;` in namespace A, or even just `friend class B::B:`. – JHBonarius Jan 27 '21 at 06:18
  • I cant able to do that,because i am not included the classB.h in classA.h – fiaazmd Jan 27 '21 at 06:38
  • That indicates you are doing something wrong: see answer below. And why are you including `classC.h` in `classA.h`? If you don't directly use it, don't include it. – JHBonarius Jan 27 '21 at 07:46

1 Answers1

1

In classA.h, when you write friend class B;, there is no way for the compiler to know that you mean Bname::B and not any other B. An unqualified B like here, will be assumed to belong to the namespace of your line, so the meaning of your line is actually friend class Aname::B.

So change that line to friend class Bname::B and you are (almost) good. Now you will get a complilation error because Bname::B is not seen from A. This can be solved by forward declaring Bname::B in the top of classA.h:

namespace Bname {
class B;
}

So to conclude, change classA.h to:

#pragma once
#include "classC.h"   // This doesn't seem necessary

namespace Bname
{
   class B;
}

namespace Aname
{
    class  A
    {
        friend class Bname::B;
    private:
        void Aclassmethod();
    };

}
cptFracassa
  • 893
  • 4
  • 14