0

Header.h

#pragma once

namespace
{
    class B;
}

namespace n1
{
    namespace n2
    {
        class A
        {
        private:
            int i;

        public:
            friend class B;
        };
    }
}

Source.cpp

#include <stdio.h>
#include "Header.h"

class B
{
public:
    void Run();
};

void B::Run()
{
    n1::n2::A a;
    a.i;
}

int main()
{
    B b;
    b.Run();
}

As we can see from above Class A is defined in header file while class B is defined in source file. I want to access private member of Class A from Class B::run(). I am not able to find the way to do this.

Swapnil
  • 1,424
  • 2
  • 19
  • 30
  • 1
    First declaration of `class B;` is inside of anonymous namespace while later is it defined in global namespace. – user7860670 Apr 17 '18 at 09:24
  • Why it was not working when class B is forward declared in unnamed namespace? – Swapnil Apr 17 '18 at 09:33
  • Because friend declaration will befriend `class B` from anonymous namespace, not `class B` from global namespace. You should always properly specify namespace when accessing names from global namespace. `friend class ::B`; Omitting `::` when accessing names from global namespace inevitably leads to program defects. – user7860670 Apr 17 '18 at 09:42
  • You know, if you want `B` to be an inaccessible implementation detail, then declaring it as a private nested class gets the job done without risking ODR violations or polluting the global namespace. – StoryTeller - Unslander Monica Apr 17 '18 at 11:01

1 Answers1

1

you are forward declaring class B in anonymous namespace

take out class B forward declaration out of the namespace and it should work

like this:

#pragma once

class B;


namespace n1
{
    namespace n2
    {
        class A
        {
        private:
            int i;

        public:
            friend class B;
        };
    }
}
Dredok
  • 807
  • 1
  • 9
  • 30
  • Why it was not working when class B is forward declared in unnamed namespace? – Swapnil Apr 17 '18 at 09:33
  • because you are declaring B in an unnamed namespace in header file and defining B in the global namespace (no namespace specifier) in the source file. If you define B in unnamed namespace in the source file then the code would run. NOTE. generally is not a good practice to declare variables in unnamed namespace in header files. – Dredok Apr 17 '18 at 09:43