feldim2425
feldim2425

Reputation: 424

Cpp Friend function has no access to private static members

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.

Upvotes: 5

Views: 1710

Answers (2)

R Sahu
R Sahu

Reputation: 206577

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

Upvotes: 2

ikleschenkov
ikleschenkov

Reputation: 972

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

Upvotes: 11

Related Questions