I am trying to define a function member of a class Extraction FRIEND with a class Descripteur, but when I compile I get the following error :
*Descripteurs.h:24:57: error: invalid use of incomplete type ‘class Extraction’ friend
void Extraction::globalSet(Descripteurs document); Descripteurs.h:19:7: error: forward declaration of ‘class Extraction’ class Extraction;*
given by the code :
//in Extraction.h
#include "Descripteurs.h"
class Extraction {
public:
Extraction(Descripteurs document);
void globalSet(Descripteurs document);
protected:
int m_value;
}
// in Extraction.cpp
#include "Extraction.h"
Extraction::Extraction(Descripteurs document){
this->globalSet(document);
}
void Extraction::globalSet(Descripteurs document){
this->m_value = document.m_nbMot; //this is why I need a friend function
cout << this->m_value << endl;
}
//in Descripteur.h
class Extraction; //forward declaration, is there a problem with this ?
class Descripteurs {
public:
friend void Extraction::globalSet(Descripteurs document);
protected:
int m_value;
};
I guess the trouble comes from the fact my classes are imbricated, because Extraction uses Descripteurs and Descripteurs has to know Exctraction to deal with the friend function. I thought the forward declaration was a solution, as explained in how comeforward or c++ friend namespace but I could not find documentation that deal with at the same time friend function, imbricated class and separated files. and if i remove "Class Extraction;" I get as expected the following error : ‘Extraction’ has not been declared friend void Extraction::globalSet(Descripteurs document);
friend function over accessor (get functions) is a choice : I don't want to make the attributes accessible from anywhere (in situation the function should take several complex attributes, and not just an int).
Can anyone tell me if I need to add some pieces of code or if there is no way to do this without using accessors ?
Any Help will be welcomed
Thanks
Alexis
Unfortunately, you can't declare a member function of a forward-declared class as friend
. See this question for possible workarounds.