0

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.

2 Answers2

0

I think you have forgotten ; at the end of your class declaration.

Following code works perfectly fine for me (gcc 4.4.5)

a.h

class A {
friend void what();
private:
    int index;
};

a.cpp

#include <iostream>
#include "a.h"

using namespace std;

void what()
{
    cout << "what" << endl;
}

int main()
{
        what();
        return 0;
}

UPDATE

You should declare what function in the a.h header file before A class declaration.

Elalfer
  • 5,312
  • 20
  • 25
  • Elalfer: I did forgot the semicolon in this post, but not in my original code. The reason your code compiled successfully was because you define the what() function in the same file that ends up calling it. I wasn't perfectly clear, but I intended to say that main() and what() definitions were in different files; i.e. there's another file not pictured (e.g. main.cpp) which includes a.h and calls the what() function. In the first example, this fails, but in the second example, it succeeds. – smackee618 Apr 13 '11 at 19:38
  • In regards to your update: You are correct in that the first example requires this, otherwise it doesn't compile. The second example, however, does not require it. This is the source of my confusion. – smackee618 Apr 14 '11 at 00:35
0

I compiled your code with g++ 4.5.1 and no error was reported.

xis
  • 24,330
  • 9
  • 43
  • 59
  • Which example: the first, the second, or both? Also, did you in fact use 3 separate files for each example? I will have to try g++ 4.5.1. – smackee618 Apr 14 '11 at 00:36
  • @smackee618: the first. i just copied and pasted your source code. I used a makefile although. – xis Apr 14 '11 at 16:17