I have a class inside a namespace and that class contains a private function. And there is a global function. I want that global function to be the friend of my class which is inside the namespace. But when I make it as a friend, the compiler thinks that the function is not global and it is inside that namespace itself. So if I try to access the private member function with global function, it doesn't work, whereas if I define a function with the same name in that namespace itself it works. Below is the code you can see.
#include <iostream>
#include <conio.h>
namespace Nayan
{
class CA
{
private:
static void funCA();
friend void fun();
};
void CA::funCA()
{
std::cout<<"CA::funCA"<<std::endl;
}
void fun()
{
Nayan::CA::funCA();
}
}
void fun()
{
//Nayan::CA::funCA(); //Can't access private member
}
int main()
{
Nayan::fun();
_getch();
return 0;
}
I also tried to make friend as friend void ::fun(); And it also doesn't help.
A friend function cannot access the private and protected data members of the class directly. It needs to make use of a class object and then access the members using the dot operator. A friend function can be a global function or a member of another class.
In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers.
Yes, In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect friends. Friends are functions or classes declared with the friend keyword.
Friend function can access all private, protected and public data members of a class. So option D is right. Friend function can access protected and public members of both classes and it can also access private members by using object of that class.
You need to use the global scope operator ::
.
void fun();
namespace Nayan
{
class CA
{
private:
static void funCA();
friend void fun();
friend void ::fun();
};
void CA::funCA()
{
std::cout<<"CA::funCA"<<std::endl;
}
void fun()
{
Nayan::CA::funCA();
}
}
void fun()
{
Nayan::CA::funCA(); //Can access private member
}
The fun() function is in the global namespace. You need a prototype:
void fun();
namespace Nayan
{
class CA
{
private:
static void funCA() {}
friend void ::fun();
};
}
void fun()
{
Nayan::CA::funCA();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With