Why is friend function showing me error that member x and y are private?

Viewed 56

Somebody please help me as I can't understand why the compiler is throwing me an error that members x and y are inaccessible even though I have given the friend function declaration?

#include<iostream>
using namespace std;
#include<math.h>
class die;

class point{
    int x , y; 
public:

    friend int die :: dist(point, point);
    point(int a,int b){
        x=a;
        y=b;
    }
    void display(){    
        cout<<"the point are ("<<x<<" , "<<y<<")"<<endl;
    }
};

class die{   
public:
    int dist(point p1 , point p2 ){
        int final;
        final= sqrt((pow((p1.x-p2.x),2))+pow((p1.y-p2.y),2));
        return final;
    }
};

int main(){
    point d(3,4);
    d.display();

    point e(3,4);
    e.display();

    die sum;
    sum.dist(d,e);

    return 0;
}
1 Answers

You cannot use incomplete names in nested specifiers use . I.e., here: friend int die::dist(point, point).

You cannot refer to a name that hasn't been declared. It's not enough to know that die exists. You also need to know that die::dist exists. In your original snippet, simple class die; does not say anything about die::dist.

By the time point is befriending die::dist, there needs to be information about dist. Just reverse the forward declaration and implement dist() after point:

class point;

class die {
public:
    int dist(point p1, point p2); // just a declaration
};

class point {
    int x, y;
public:

    friend int die::dist(point, point);

    point(int a, int b) {
        x = a;
        y = b;
    }

    void display() {
        cout << "the point are (" << x << " , " << y << ")" << endl;
    }
};

int die::dist(point p1, point p2) { // implementation possible since we know about internals of point
    int final;
    final = sqrt((pow((p1.x - p2.x), 2)) + pow((p1.y - p2.y), 2));
    return final;
}

Additionally, I see no reason for dist to be a member function of die. It can either be static, or simply be a free function.

Related