Skip to main content

City class with operator overloading

Short answer

Operator overloading syntax: return_type ClassName::operator op(args) { … } as member function. For City, overload + to return a City with summed DistFromKtm and – to return absolute difference. With Pokhara (200 km) and Dhangadi (680 km), sum = 880 km, distance = 480 km.

Explain the syntax of operator overloading. Create a class named City that will have two member variables CityName (char[20]) and DistFromKtm (float). Add member functions to set and retrieve the CityName and DistFromKtm separately. Add operator overloading to find the distance between the cities (just find the difference of DistFromKtm) and sum of distance of those cities from Kathmandu. In the main function, initialise three city objects. Set the first and second city to be Pokhara and Dhangadi. Display the sum of DistFromKtm of Pokhara and Dhangadi and distance between Pokhara and Dhangadi.

Syntax of operator overloading

return_type ClassName::operator op (argument_list) { body }

operator is a keyword and op is the operator symbol. As a member function, a binary operator takes one argument (the right operand); the left operand is the calling object. c3 = c1 + c2; is translated to c3 = c1.operator+(c2);.

Program

Assumptions: operator+ returns a City whose DistFromKtm is the sum; operator- returns the distance between two cities (absolute difference) as a float. Approximate distances used: Pokhara 200 km, Dhangadi 680 km.

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;

class City {
    char CityName[20];
    float DistFromKtm;
public:
    void setName(const char *n)  { strcpy(CityName, n); }
    void setDist(float d)        { DistFromKtm = d; }
    const char* getName()        { return CityName; }
    float getDist()              { return DistFromKtm; }

    // sum of distances from Kathmandu
    City operator+(City c) {
        City t;
        strcpy(t.CityName, "Sum");
        t.DistFromKtm = DistFromKtm + c.DistFromKtm;
        return t;
    }

    // distance between two cities (difference of DistFromKtm)
    float operator-(City c) {
        return fabs(DistFromKtm - c.DistFromKtm);
    }
};

int main() {
    City c1, c2, c3;
    c1.setName("Pokhara");  c1.setDist(200);
    c2.setName("Dhangadi"); c2.setDist(680);

    c3 = c1 + c2;
    cout << "Sum of DistFromKtm of " << c1.getName() << " and "
         << c2.getName() << " = " << c3.getDist() << " km" << endl;
    cout << "Distance between " << c1.getName() << " and "
         << c2.getName() << " = " << c2 - c1 << " km" << endl;
    return 0;
}

Output:

Sum of DistFromKtm of Pokhara and Dhangadi = 880 km
Distance between Pokhara and Dhangadi = 480 km

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →