Reputation: 133
class A{
public:
void printer(){
B obj;
obj.private_data = 10; // <- fails, says member inaccessible
}
}
class B{
friend void A::printer();
private:
int private_data;
}
is it possible for printer function to access private members of class B? i tried to pass an obj of B as arg to printer but it still failed
Upvotes: 3
Views: 1493
Reputation: 7100
Class A
doesn't know about B
to use it. Hence, postpone the definition of the function printer()
until you define B
, and if you need an instance of B
to be a member var in A
then make a forward declaration for B
to declare a B*
in A
.
Hence, use something like what follows:
class A {
public:
void printer();
};
class B {
friend void A::printer();
private:
int private_data;
};
void A::printer() {
B obj;
obj.private_data = 10; // <- No longer fails
std::cout << obj.private_data;
}
int main() {
A a;
a.printer();
}
Upvotes: 5
Reputation: 117298
Why Friend Function cannot access private members of a class?
They can, but you may need to split the definition of the class up a bit.
Imaginary files added:
Define A
(file a.hpp
):
class A {
public:
void printer();
};
Define B
(file b.hpp
):
#include "a.hpp" // B must see the definition of A to befriend a member function
class B {
friend void A::printer();
private:
int private_data;
};
Define A
's member function (file a.cpp
):
void A::printer() {
B obj;
obj.private_data = 10;
}
Upvotes: 3
Reputation: 845
To access B
, you first need to define it. Thus, you can just declare the method printer
and define it after you have defined the class B
.
class A {
public:
void printer();
};
class B {
private:
friend class A;
int private_data;
};
void A::printer() {
B obj;
obj.private_data = 10;
}
Note, you probably want to move your methods out of your class definition anyways and into a separate .cpp
file. Methods defined inside the class are implicitly marked as inline
which might not be what you expect.
Upvotes: 3