I'm not able to call a friend function in my main program. Moreover, I have three files, my main.cpp program, a foobar.h and a foobar.cpp for the functions of my class. When I try to call the friend myClass* foobarfunction in my main.cpp program, I get the following error:
[Error] 'MyFunction' was not declared in this scope.
I'm compiling the program in the Dev C++ Environment, using GCC 4.9.2.
My main program where I call the foobarfunction is the following, where headers.h contains all my header files.
#include "headers.h"
a = MyFunction(something1, something2);
Then the foobar.h file is:
class MyClass {
public:
MyClass();
virtual ~MyClass();
private:
friend MyClass* MyFunction(const int a, const int* b=0, const double c=1., const double d=2.);
};
Also my foobar.cpp program contains the MyFunction program as follows:
#include "MyClass.h"
MyClass::MyClass() {...}
MyClass::~MyClass() {...}
MyClass* MyFunction(const int a, const int* b, const double c, const double d) {
return nullptr;
}
Is it possible that the version of the GCC compiler creates the error? Please let me know if I need to post more segments of my code. Thanks.
PS: I have tried also compiling the code on linux GCC version g++ 11.2.0 and on Windows with newer g++ version but I'm getting a lot of errors friend declaration of '' specifies default arguments and isn't a difinition, that's why I'm trying with an older compiler. This program was writen in 2010.
The friend declaration
is not visible outside the class where it is declared until its declaration will appear outside the class.
From the C++ 17 Standard (10.3.1.2 Namespace member definitions)
You need to include a declaration of the function outside the class in the header
foobar.h.Also the default arguments may be present in the friend function declaration that is its definition and is only the function declaration in the translation unit.
From the C++ 17 Standard (11.3.6 Default arguments)