3
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

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
g0x0
  • 93
  • 7
  • I believe the _recommended edit_ was for one of the answers - not your question. On that assumption, I'm rolling your edit back. – Drew Dormann Sep 03 '21 at 15:13
  • The code in the question did not produce the error message that's paraphrased in the comment. The code won't compile because at `B obj;` there is no `B`. – Pete Becker Sep 03 '21 at 16:24

3 Answers3

5

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();
}

Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
asmmo
  • 6,922
  • 1
  • 11
  • 25
3

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;
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
3

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.

H. Rittich
  • 814
  • 7
  • 15