-1

Why is the global function void showA(A& x) able to access private members of class A? I know that the function with similar method signature is declared as a friend of class A but the global showA() isn't the same as the function showA(A&) declared inside class A.

#include <iostream> 

class A { 
    int a; 

public: 
    A() { a = 0; } 


    friend void showA(A&); 
}; 

void showA(A& x)  function
{ 


    std::cout << "A::a=" << x.a; 
} 

int main() 
{ 
    A a; 
    showA(a);
    return 0; 
}
  • 1
    That's what `friend` does. The given class/function has full access. The code you're showing has matching function signatures, so full access. – Mark Storer Oct 30 '19 at 12:08
  • 7
    What makes you think they are different functions? `friend void showA(A&)` declares (and befriends) a function of that signature in the scope *surrounding* the class (declaring it inside the class, i.e. as member function, would be very pointless - what would `friend` do in that case?). That's the very same function you provide a definition for afterwards. – Max Langhof Oct 30 '19 at 12:08
  • 1
    @Ajay Shukla What is void showA(A& x) function? – Vlad from Moscow Oct 30 '19 at 12:20
  • `void showA(A& x) function` doesn't compile on my machine, because the `function`. What purpose does `function` supposed to serve there? – Eljay Oct 30 '19 at 12:31

1 Answers1

2

I know that the function with similar method signature is declared as a friend of class A

Yes, functions declared as friend can access private members.

but the global showA() isn't the same as the function showA(A&) declared inside class A.

It is not clear how you come to that conclusion. You declare that void showA(A&) is a friend and then you provide a definition for void showA(A&). They are one and the same function.

PS: Note that if you had a defined a function with signature showA() as you wrote in the text, then that would indeed be a different function with no access to private members of A.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185