Skip to main content

mdistance and edistance addition via friend

Short answer

A friend function accesses private members of both classes. It converts mdistance to cm (meter*100+cm) and edistance to cm ((feet*12+inch)*2.54), sums them, and converts back to meters and centimeters. Example: 2m 50cm + 3ft 6in =3m 56.68cm.

Create a class mdistance to store the values in meter and centimeter and class edistance to store values in feet and inches. Perform addition of object of mdistance and object of edistance by using friend function.

A friend function is not a member of a class but can access its private members if the class declares it with the keyword friend. Here one function add() is declared as a friend of both classes, so it can read the private data of both mdistance (metre, centimetre) and edistance (feet, inches).

Assumptions: 1 m = 100 cm, 1 ft = 12 in, 1 in = 2.54 cm. The sum is displayed in metres and centimetres.

#include <iostream>
using namespace std;

class edistance;                 // forward declaration

class mdistance {
    int meter;
    float cm;
public:
    void getdata() {
        cout << "Enter meter and centimeter: ";
        cin >> meter >> cm;
    }
    friend void add(mdistance, edistance);
};

class edistance {
    int feet;
    float inch;
public:
    void getdata() {
        cout << "Enter feet and inches: ";
        cin >> feet >> inch;
    }
    friend void add(mdistance, edistance);
};

// friend of both classes
void add(mdistance m, edistance e) {
    // convert everything to centimetres
    float total_cm = m.meter * 100 + m.cm
                   + (e.feet * 12 + e.inch) * 2.54;
    int mt = (int)(total_cm / 100);
    float c = total_cm - mt * 100;
    cout << "Sum = " << mt << " m " << c << " cm" << endl;
}

int main() {
    mdistance m;
    edistance e;
    m.getdata();
    e.getdata();
    add(m, e);
    return 0;
}

Sample run:

Enter meter and centimeter: 2 50
Enter feet and inches: 3 6
Sum = 3 m 56.68 cm

Check: 3 ft 6 in = 42 in = 106.68 cm; 2 m 50 cm = 250 cm; total = 356.68 cm = 3 m 56.68 cm.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →