akris
akris

Reputation: 57

C++ friend function of class not able to access the encapsulated class

Hi I am trying to access the private member x of class A from class B

below code shows the way i found but getting error any suggestion would be helpful to achieve my objective. Thanks in advance

> main.cpp: In member function ‘void B::bfun(A*)’:
main.cpp:19:9: error: invalid use of incomplete type ‘class A’
     Aref->x = 1;
         ^~
main.cpp:11:7: note: forward declaration of ‘class A’
 class A;
       ^
main.cpp:20:11: error: ‘x’ was not declared in this scope
     cout<<x;
       ^

code:

    #include <iostream>
using namespace std;
class A;
class B{
    private:
    public:
    void bfun (A* Aref);
};
void B::bfun(A* Aref)
{
    Aref->x = 1;
    cout<<x;
}

class A{
    private:
    int x;
    B b_obj;


    public:
    void afun();
    friend void B::bfun(A*);
};
void A::afun()
{
  x=0;
  b_obj.bfun(this);
}


int main()
{
    printf("Hello World");
    A aobj;
    aobj.afun();
    return 0;
}

Upvotes: 1

Views: 72

Answers (2)

Math Lover
Math Lover

Reputation: 148

Since x is not a direct member of B, but you access it anyway through A, you should write:

void B::bfun(A* Aref)
{
    Aref->x = 1;
    std::cout<< Aref->x << '\n' ;
}

Upvotes: 0

WhozCraig
WhozCraig

Reputation: 66224

The listed error isn't about permissive access to a friend; it's about realization of what is an incomplete type due to how you ordered your code for class declarations and member implementation. Changing your code to order B::bfun after the proper class A declaration will address that problem.

#include <iostream>
class A;

class B
{
private:
public:
    void bfun (A* Aref);
};

class A{
private:
    int x;
    B b_obj;
public:
    void afun();
    friend void B::bfun(A*);
};

void B::bfun(A* Aref)
{
    Aref->x = 1;
    std::cout<< Aref->x << '\n' ;
}

void A::afun()
{
    x=0;
    b_obj.bfun(this);
}

int main()
{
    A aobj;
    aobj.afun();
    return 0;
}

Output

1

See it live

Upvotes: 2

Related Questions