Parameterized constructor as friend class in c++

Advertisements

I want to find the distance between two points. In class point, the parameterized constructor, point(int a, int b), takes two integers and assigns them to the private variables, x and y. The displaypoint() member function prints "(x,y)". It also has friend class, dist.

The class dist has only a constructor that takes two point class objects as arguments and should display a calculated diff variable.

However, my dist class gives an error.

Here’s the code.

// Parameterized Constructor using Friend Class Example :-
#include <iostream>
#include <cmath>
using namespace std;

class point
{
    int x, y;
    friend class dist;

public:
    point(int a, int b)
    {
        x = a;
        y = b;
    }
    void displayPoint()
    {
        cout << "The Point is : (" << x << "," << y << ")" << endl;
    }
};
class dist  // shows error here
{
public:
    void dist(point p1, point p2)
    {
        int x_diff = (p2.x - p1.x);
        int y_diff = (p2.y - p1.y);
        int diff = sqrt(pow(x_diff, 2) + pow(y_diff, 2));
        cout << "The difference is : " << diff << endl;
    }
};
int main()
{
    point p(1, 2);
    point q(4, 6);

    point c(1, 1);
    point d(1, 1);

    point e(1, 0);
    point f(70, 0);

    dist(p, q);
    dist(c, d);
    dist(e, f);
    return 0;
}

If I remove class dist and make dist() as a friend function instead of a constructor, the code works.

void dist(point p1, point p2)
{
    int x_diff = (p2.x - p1.x);
    int y_diff = (p2.y - p1.y);
    int diff = sqrt(pow(x_diff, 2) + pow(y_diff, 2));
    cout << "The difference is : " << diff << endl;
}

>Solution :

As mentioned in the comments, your primary issue is that you have declared the dist constructor with a return type (even though that type is void, the declaration is still a syntax error). So, just remove that return type.

Also, you shouldn’t be using the pow function with integer types; in fact, you shouldn’t be using int as the x_diff and y_diff types, nor for the resultant diff; an integer result for that answer will, most often, be quite wrong (especially if either the x or y differences are small). Use double for all those values:

class dist  // shows error here
{
public:
    dist(point p1, point p2) // Constructor doesn't have a return type
    {
        double x_diff = static_cast<double>(p2.x - p1.x);
        double y_diff = static_cast<double>(p2.y - p1.y);
        double diff = sqrt(pow(x_diff, 2) + pow(y_diff, 2));
        cout << "The difference is : " << diff << endl;
    }
};

Leave a Reply Cancel reply