82. Add Two Distances

#include <iostream>
#include <cstdint>

using namespace std;

class Distance {
private:
    int32_t meters;

public:
    Distance(int32_t m) : meters(m) {}

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

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

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

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

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

    return 0;
}

Explanation & Logic Summary:

The + operator is overloaded as a const member function.

  • It takes another Distance object by constant reference
  • It does not modify either operand
  • It returns a new Distance object whose meters value is the sum

Using int32_t ensures:

  • Fixed-width behavior across embedded platforms
  • No ambiguity about integer size
  • Predictable arithmetic with defined constraints

Firmware Relevance & Real-World Context:

In embedded firmware, physical quantities such as distances, offsets, or sensor deltas are often modeled using small value-type classes.

This problem practices:

  • Operator overloading with value semantics
  • Fixed-width integer usage (int32_t)
  • Const-correctness
  • Safer domain modeling instead of raw integers

These patterns are commonly used in motion control, sensor processing, and low-level measurement code on microcontrollers.

 

 

 

 

 

Loading...

Input

5 7

Expected Output

Total=12