Definition of friend inside class - c++

Can i put definition of friend function / class inside another class? I mean something like this:
class Foo
{
friend void foo() {} // 1
friend class Bar {}; // 2
};
gcc compiles friend function, but can't compile friend class.

You can define a friend function in the friend declaration, and it has interesting behavior that cannot be obtained any other way (in the case of the enclosing type being a template).
You cannot define a friend class in the friend declaration, and there is no need for that. If you want to create a new type inline with full access, you can just create a nested type. Being a member it will have full access to the enclosing type. The only difference is that the type will not be found at namespace level, but you can add a typedef if needed (or alternatively, define the class at namespace level and just declare the friendship inside the class).
class Outer {
int x;
class Inner {
static void f( Outer& o ) { o.x = 5; } // fine
};
};

n3337 11.3/2
A class shall not be defined in a friend declaration. [ Example:
class A {
friend class B { }; // error: cannot define class in friend declaration
};
—end example ]
But you can use something like
class Foo
{
friend void foo() {} // 1
class Bar { };
friend class Bar; // 2
};

You can make a nested class which, according to defect report 45, has access to the private members of the class. Is this what you meant?
"A nested class is a member and as such has the same access rights as any other member."
This may not work in all compilers because prior to this C++ standards defect report, nested classes were given no special access.

Change the code to:-
class Foo
{
friend void foo() {} // 1
friend class Bar ; // 2
};

Related

If class Outer is my friend, is class Outer::Inner too?

The following code compiles on MSVC:
#include <iostream>
class Bob
{
int a;
friend class Outer;
};
class Outer
{
class Inner
{
void f(Bob obj)
{
std::cout << obj.a; //OK
}
};
};
So it seems that if Outer is a friend of Bob, so is Inner, automatically. I am reading the Friends chapter of the standard and am unable to find a clause that would confirm or refute this.
Is this legal, and if so, what's the chapter and verse?
[class.access.nest]/1 states that
A nested class is a member and as such has the same access rights as any other member
So I believe yes, this is standard behavior.
Let's say that Outer has a member function foo(). That function, of course, will have access to Bob's members. To my understanding, the part that I quoted implies that any nested class inside Outer would have the same access rights as foo(), thus having the ability to access Bob's members.
It is also worth noting that the standard contains the following example ([class.friend]/2), note the usage of A::B in Y:
class A {
class B { };
friend class X;
};
struct X : A::B {
// OK: A::B accessible to friend
A::B mx; // OK: A::B accessible to member of friend
class Y {
A::B my; // OK: A::B accessible to nested member of friend
};
};

enclosing scope

what's wrong with this code?
class matrix{
private:
friend transpose(const matrix&);
friend class invert;
public: //...
};
matrix (*p)(const matrix&)=&transpose; //error: no transpose() in scope.
what does the statement means "a friend declaration does not introduce a name into enclosing scope".This problem does not occur when friend keyword is removed
The difference between the declaration of transpose() as a friend and without the friend declaration is that if you declare "friend transpose()" all you are doing is telling the compiler that a function friend with the signature shown in the friend declaration can have access to the private members of an object of type matrix. It does not declare a function transpose() with this signature - you still have to do this outside the scope of the matrix class.
If you remove the 'friend' keyword, you are declaring a member function transpose() inside the class matrix, so the compiler actually has seen a function it can take the address of.
§7.3.1.2 [namespace.memdef] p3
[...] If a friend declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup or by qualified lookup until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). [...]
See also this question of mine.
Friend functions are functions that are not members of a class but
they still have access to the private members of the class.
I should point out that a friend function declaration
may be placed in either the private section or the public section,
but it will be a public function in either case, so it is clearer to
list it in the public section.
class MyClass
{
private:
int data;
public:
MyClass(int value);
friend void myFriend(MyClass *myObject);
};
void myFriend(MyClass *myObject)
{
cout << myObject->data<< endl;
}
MyClass::MyClass(int value)
{
data = value*2;
}
int main()
{
MyClass myObject(3);
myFriend(&myObject);
}
So, you need to define the friend function after you declare it.

Can a private operator be accessible from outside?

i.e. if I define operators == and + in my class in a private section, can they be accessible from main?
It works in MSVS 2008 and 2010 but for me it seems to be a bug in a compiler. Is it so?
Functions or members declared under private access specifier will not be accessible outside the class member functions.
There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
Friends to the rescue!
Declaring a function as friend inside another class allows that function to access all the member functions inside the class irrespective of the access specifier rules. friend It is a way to bypass the access specifier rules laid out in C++. Similary, a class declared as friend inside another class will allow the class being declared as friend to have access to all the members of the class. Note that the friend declaration can be given under any access specifer and it will have the same effect.
An source code example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
friend void doSomething(MyClass obj);
};
void doSomething(MyClass obj)
{
obj.a = 10; //Allowed
obj.b = 20; //Allowed,
obj.c = 30; //Allowed,
}
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
So in your usage if you are using friend then you can have access to the private members of the class or else your compiler is buggy you should consider changing it!
You will have to show the code to get a sensible explanation of why the compiler is accepting it. My guess is that you are implementing them as friend free functions. At any rate, for the sake of argument, assume you have:
class bar {
friend bool operator==( bar const &, bar const & ) {
return true;
}
bar operator+( bar const & ) {
return *this;
}
};
int main() {
bar a, b;
a == b; // ok
//a + b; // nok: operator+ is private from this context
}
And now the explanation. In the example, operator+ is declared as a member function inside a private section, as such, access specifiers apply and unless main is a friend of the class it will not have access to it. On the other hand operator== is implemented as a free function (even if the definition is provided inside the class braces) and access specifiers do not apply there.
The code is almost equivalent (there is a small difference when it comes to lookup) to:
class bar {
friend bool operator==( bar const &, bar const & ); // just declare as friend
//...
};
bool operator==( bar const &, bar const & ) {
return true;
}
Where it is much simpler to reason about accessibility of operator== from the main function.
Yes, it is a bug. They are accessible only by friend functions and friend classes. All other shouldn't have access to private section.
The first answer is : No. If its accessible from outside then what is the point of being it private?
However, there is a twist.
If you make main() friend of the class, then its accessible only from main(). So the second answer is : it actually depends: Only member functions and friends can access the private member of a class.
class A
{
int data; //private
friend int main(); //make main() friend of A
};
int main()
{
A a;
a.data = 100; //okay - main() is a friend of class A
}
void f()
{
A a;
a.data = 100; //error - f() is not a friend of class A
}
That means, I infer that operator== and operator+ must be friends of the class in your code.
If you haven't added a friend declaration for main (don't know if that is even possible), the answer is no, so you apparently have found a compiler bug.

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

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();
}
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.
Because friend struct S; declares N::S class but you need ::S class.
Try writing out friend struct ::S;.
At the moment, the non-existent N::S is assumed. This fix specifies the global namespace, a bit like how the leading / on a Linux path specifies the filesystem root.

Definition of friend class and accessor sections

When defining a class as a friend class, does it matter in which accessor section the definitions is placed, and if so does that change the members the friend has access to?
class aclass
{
private:
// friend bclass;
public:
// friend bclass;
protected:
// friend bclass;
};
class bclass
{};
Access specifiers do not apply to friend function/Class
You can declare the Friend Function or Class under any Access Specifier and the Function/Class will still have access to all the member variables(Public,Protected & Private) of that Class.
Once you place friend class/function inside a given class (say 'aclass') anywhere. It will have access to all defined members of the class (irrespective of public/private/protected); for example:
class aClass
{
public: int pub; void fun1() {}
protected: int pro; void fun2() {}
private: int pri; aClass(const aClass& o);
friend void outsider ();
};
Friend function outsider() can access pub, pro, pri, fun1, fun2; but not aClass copy constructor in this case (if it's not defined anywhere).
Friend functions aren't placed inside any accessors by convention, because by definition they aren't part of the class. You might do something like this:
class Elephants
{
//friend void notAMemberFuncion(argument 123);
public:
// member functions;
protected:
// data members;
};
The friend class/function can access all the private/protected/public members of class, which access section the friend class/function is placed doesn't make any difference.
It's suggested to put friend class/function in the public section, because friends is part of the class interface.