1
votes

Hi I am trying to understand the scope of friend functions and I get a "not declared in scope" error. Here is my code:

//node.h
class Node{

public:

  int id;
  int a;
  int b;

  friend int add(int,int);

  void itsMyLife(int);
  Node();
};

//node.cpp
Node::Node(){
  a=0;
  b=0;
  id=1;
}

void Node::itsMyLife(int x){

  cout<<"In object "<<id<<" add gives "<<add(x,a)<<endl;

}

//routing.cpp
#include "node.h"

int add(int x, int y){

     return x+y;
}

//main.cpp
#include "node.h"

int main(){

return 0;
}

I get the error "add not declared in this scope" in node.cpp. Why do I get this error when I have declared the function in the class scope? Any help will be appreciated. Thanks

3
AFAIK friend declaration is also a forward declaration. If I'm right there shouldn't be an error. Maybe it sees it as in the class scope (though that doesn't make much sense for a friend function), try adding :: before add in the friend declaration to declare it is in the global scope and not class scope. Maybe it will help. - selalerer
Actually the problem disappears if I define the add function in node.cpp. But I want to define it in a separate file. How can I do that? - user2105632

3 Answers

2
votes

Inside your node class you declare a friend function int add (int, int). However, currently the compiler hasn't encountered the function yet and therefore it is unknown.

You could make a separate header and source file for your add function. Then in node.h include you new header. Because in the file where you declare Node the function add is not known currently.

So you might make a add.h and a add.cpp file for example and include add.h before declaring Node. Don't forget to compile add.cpp as well.

2
votes

Its a bug on the the Linux side. The code should work. I have code right now that compiles fine on the Windows side and when I move it to the Linux side I get the same error. Apparently the compiler that you are using on the Linux side does not see/use the friend declaration in the header file and hence gives this error. By simply moving the of the friend function's implementation in the C++ file BEFORE that function's usage (e.g.: as might be used in function callback assignment), this resolved my issue and should resolve yours also.

Best Regards

1
votes

You haven't actually declared the function.

extern int add(int, int);