hello,

I want to make a little program with a friend method but there is a bug.
In my example code, I have a class A which have the method f from clas B as friend.

files:

A.h

#ifndef _A_H
#define	_A_H
 
#include "B.h"
 
class A {
 
public:
    A();
    friend void B::f(A);
 
private:
    int x;
};
 
#endif	/* _A_H */

A.cpp

#include "A.h"
 
 
A::A() {
    x=10;
}

B.h

#ifndef _B_H
#define	_B_H
class A;
 
class B {
public:
    B();
    void f(A);
private:
 
};
 
#endif	/* _B_H */

B.cpp

#include "B.h"
#include <iostream>
using namespace std;
 
void B::f(A a){
    cout << a.x;
}
 
 
B::B() {
}
 
int main(int argc, char argv[]){
    A ex;
    f(ex);
 
    return 0;
 
}

here is the issue:

B.cpp: In member function `void B::f(A)':

B.cpp:12: error: `a' has incomplete type

B.h:10: error: forward declaration of `struct A'

B.cpp:13: error: invalid use of undefined type `struct A'

B.h:10: error: forward declaration of `struct A'

B.cpp: In function `int main(int, char*)':

B.cpp:21: error: aggregate `A ex' has incomplete type and cannot be defined

B.cpp:22: error: `f' undeclared (first use this function)

B.cpp:22: error: (Each undeclared identifier is reported only once for each function it appears in.)

I searched in some tutorials and in some books but in vain.
can you help me?

olivier.

Sky Diploma commented: Code Tags on First Post !! :) +3

I think that you should be including "A.h" instead of "B.h" because the file B.h has a declaration of the class A and no Definitions :)

I changed all the B.h in A.h (anyway the file A.h has the statement #include "B.h") but there is still the issue.

olivier.

but thank you for your answer.

olivier.

f(ex) is an instance method.

B p;
 p.f(ex);

and include "A.h" in B.cpp.

Others suggestion is right and should fix the code.:
1. change the "B.h" to A.h while including in the 1st line of B.cpp
2. You are calling f() without an object. Note that f() is a member of B so you need to create an object of B and call f()
Thus, you B.cpp should like:

#include "A.h"
#include <iostream>
using namespace std;
 
void B::f(A a){
    cout << a.x;
}
 
 
B::B() {
}
 
int main(int argc, char argv[]){
    A ex;
    B b;
    b.f(ex);
 
    return 0;
 
}

Compile like this : g++ -o out B.cpp A.cpp

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.