35. Add Two Distances

#include <iostream>
using namespace std;

class Distance {
private:
    int meters;
public:
    Distance(int m) : meters(m) {}

    Distance operator+(const Distance& other) const {
        return Distance(meters + other.meters);
    }

    int getMeters() const {
        return meters;
    }
};

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

    Distance d1(a);
    Distance d2(b);

    Distance total = d1 + d2;
    cout << "Total=" << total.getMeters();

    return 0;
}

Solution Details

  • Only operator+ is added.
  • It returns a new Distance with the sum of both objects’ meters.
     

👉 In simple words:
 This lets you write d1 + d2 just like normal integers, but for your custom class.

Significance for Embedded Developers

  • This style of code makes dealing with domain-specific values (like sensor readings, distances, time intervals) natural and safe.
     

You can model physical quantities directly instead of juggling raw integers everywhere.
 

Loading...

Input

5 7

Expected Output

Total=12