30. Sum of Two Objects

#include <iostream>
using namespace std;

class Distance; // forward declaration

class Point {
private:
    int x;
public:
    Point(int v) : x(v) {}
    friend void sumValues(const Point&, const Distance&);
};

class Distance {
private:
    int d;
public:
    Distance(int v) : d(v) {}
    friend void sumValues(const Point&, const Distance&);
};

void sumValues(const Point& p, const Distance& dist) {
    cout << "Sum=" << (p.x + dist.d);
}

int main() {
    int a, b;
    cin >> a >> b;

    Point p(a);
    Distance dist(b);

    sumValues(p, dist);

    return 0;
}

 

Solution Details

  • The function name is explicitly sumValues.
     
  • It is declared as a friend in both classes, so it can access p.x and dist.d directly.
     
  • Without friend, these variables are private and inaccessible.
     

👉 In simple words:
 Normally, the private variables are hidden. The function sumValues is like a helper that both classes trust, so it can open the box and add the numbers inside.

Significance for Embedded Developers

  • In firmware, sometimes two independent modules (like two sensors or two drivers) need a shared utility to inspect their private states (for debugging or combining values).
     
  • A friend function allows this without making everything public, keeping the design safe but flexible.

     
Loading...

Input

5 7

Expected Output

Sum=12