Let's say I have a header file a.h and a source file a.cpp. When I try to compile this and call what() from a different file (e.g. main.cpp) which includes a.h:
a.h:
class A {
friend void what();
public:
int index;
};
a.cpp:
#include "a.h"
#include <iostream>
void what() {
std::cout << "what" << std::endl;
}
It fails, as expected (error: 'what' was not declared in this scope). However, when I do the same thing with this:
a.h:
class A {
friend void what(A *thing);
public:
int index;
};
a.cpp:
#include "a.h"
#include <iostream>
void what(A *thing) {
std::cout << thing->index << std::endl;
}
It compiles and runs just fine on g++ 4.4.1 (assuming "index" has been initialized, of course). I don't know much about C++, but I would assume that, by passing the object pointer to the function, the function somehow became available to the global scope (i.e. gets "promoted" in order to be able to "see" an object which previously existed on the same scope as it). I haven't tried this with other kinds of functions yet, but, when using g++ and friend functions, I get this behavior. Is this supposed to happen in C++?
Thanks and sorry if this is a noobish question, my friend Google was failing me.