Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cpp Friend function has no access to private static members

Tags:

c++

I have a class with a private static variable. The main function should change the value in the variable, but even if I set the main function as a friend of the class the compiler tells me that the variable is private and not accessible from main.

Example:

ClassA.h:

namespace nameA{    

class ClassA {
    private:
        static int varA;

    public:
        ClassA(){};

    friend int main(void);
};
}

ClassA.cpp:

namespace nameA{

int ClassA::varA = 0;

}

main:

int main(void){
    ClassA::varA = 42; //ERROR
}

I don't know if "friend" also allows access to static members or if I have to find another solution.

like image 726
feldim2425 Avatar asked Jul 31 '17 14:07

feldim2425


2 Answers

It because friend function main in ClassA is located in nameA namespace.

If you want to declare as friend the int main(void) function, that located in global scope, you should do it this way:

friend int ::main(void);

Whole source (compiled in VS2015):

int main(void);

namespace nameA {

    class ClassA {
    private:
        static int varA;

    public:
        ClassA() {};

        friend int ::main(void);
    };
}

namespace nameA {
    int ClassA::varA = 0;
}

int main(void) {
    nameA::ClassA::varA = 42;
    return 0;
}
like image 142
ikleschenkov Avatar answered Sep 30 '22 19:09

ikleschenkov


Your friend declarations grants friendship to a function named main in the namespace nameA, not the global main function.

Your code is equivalent to

namespace nameA
{
   int main(void);

   class classA
   {
      ...
      friend int main(void);
   };
}

You need to declare main before the namespace starts.

int main(void);

namespace nameA
{    
   class classA
   {
      ...
      friend int main(void);
   };
}

should work

like image 29
R Sahu Avatar answered Sep 30 '22 19:09

R Sahu