Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I change a private member of a class from a friend class in a different namespace?

Tags:

c++

I am finding trouble accessing a private member of a class from a friend class.

The class that holds the private member I want to change and the class where the change is made are in different namespaces.

The friend class is defined after the class holding the data, so I've tried to forward declare the friend class outside the namespace.

g++ says that I can't modify the member because it's private, visual studio seems to think it's fine.

Am I doing some weird non-standard thing here? Why can't I change the member? Here is a simplified snippet that represents my problem:

struct S;

namespace N
{
    class A
    {
        int m;
    public:
        A():m(5){};
        friend struct S;
    };

}

using namespace N;

struct S
{
    A& a;
    S(A& a):a(a) {}
    void changeA(){ a.m = 9; }
};

int main()
{
    A a;
    S s(a);
    s.changeA();
}
like image 804
Jacobo de Vera Avatar asked May 14 '11 16:05

Jacobo de Vera


1 Answers

friend struct ::S;

what you are really doing with

friend struct S;

is declaring as friend the class N::S (which is defined nowhere).

Edit: To back up my idea that gcc behavior is correct and VC++ has a bug.

7.3.1.2/3

If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. [...] When looking for a prior declaration of a class or function introduced by a friend declaration, scopes outside the innermost enclosing namespace scope are not considered.

like image 194
AProgrammer Avatar answered Nov 10 '22 07:11

AProgrammer