declare a class member function as a friend function of another class

i have created 2 classes (class A and class B) i have declared class A before class B(forward declaration of class A). i have created a public function in class B with name funB(A temp). in the class A i have declared the funB function of class B as a friend function of class A.

i am getting error when i write the defination of funB() inside the class B defination. but when i write the defination of funB() function outside the class B then it works fine.

can anyone explain why this is happening ???? i am very confused.

// ERROR
class A;
class B{
    public:
        void funB(A temp){
            printf("friend function");
        }
};

class A{
    public:
        friend void B::funB(A);
};

above code has showing me ERROR

👇the below code works fine.

class A;
class B{
    public:
        void funB(A temp);
};

class A{
    public:
        friend void B::funB(A);
};

void B::funB(A temp){
    printf("friend function");
}

please answer to my problem.

Upvotes: 0

Views: 86

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123114

This has nothing to do with friends. void funB(A temp) requires A to be a complete type. A must be defined before you can define B::funB because implicitly it uses methods of A (a copy is made to copy a parameter to the argument of the function, then when the function returns temp must be destroyed by calling a destructor).

In the first example you try to define B::funB before A is complete. Thats an error.

In the second example you define B::funB when A is complete.

PS: I suppose reading the error message would have helped to understand. It should mention something about A being incomplete when you define B::funB.

Upvotes: 2

Related Questions