user2105632
user2105632

Reputation: 781

Friend function not declared in this scope error

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

Upvotes: 2

Views: 7689

Answers (4)

sundar karthik
sundar karthik

Reputation: 1

#include "node.h"
#include <iostream>
using namespace std;
class Node{
public:
    int id;
    int a;
    int b;

    friend int add(Node &a);
    void itsMyLife(int);
    Node();
};

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

void Node::itsMyLife(int x):b(x){
    cout<<"In object "<<id<<" add gives "<<add(Node &a)<<endl;
}

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

int add(Node &a){
    return a.b+a.y;
}

//main.cpp

int main(){
    Node n;
    n.ItsMyLife(15);
    cout<<add(n);
    return 0;
}

This should work fine - I guess. The syntax for "friend" function is -- friend {returntype} {functionname} (class_name &object_name). To access any of the members of the class use object_name.variable_name.

Upvotes: 0

DJR
DJR

Reputation: 21

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

Upvotes: 2

hetepeperfan
hetepeperfan

Reputation: 4411

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.

Upvotes: 2

kfsone
kfsone

Reputation: 24249

You haven't actually declared the function.

extern int add(int, int);

Upvotes: 1

Related Questions