Search code examples
c++friendprivate-members

Access private variable of class defined in header from class defined in source file


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.


Solution

  • 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;
            };
        }
    }