Object Oriented Programming - Old Questions

2. Explain the concept of operator overloading? List the operators that cannot be overloaded. Write programs to add two object of distance class with data members feet and inch by using by using member function and friend function.

10 marks | Asked in 2076

In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide the operators with a special meaning for a user-defined data type, this ability is known as operator overloading. For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using +. Other example classes where arithmetic operators may be overloaded are  Distance which has data member feet and inch, Complex Number etc.

Operator that cannot be overloaded are as follows:

  • Scope operator (::)
  • Sizeof
  • member selector(.)
  • member pointer selector(*)
  • ternary operator(?:)

Program

#include <iostream>

using namespace std;

class Distance

{

    private:

        int feet, inch;

    public:

        void readDistance(void)

        {

            cout << "Enter feet: ";

            cin >>feet;

            cout << "Enter inch: ";

            cin >>inch;

        }

        void displayDistance(void)

        {

            cout << "Feet:" << feet << "\\t" << "Inches:" << inch << endl;

        }

        friend Distance operator+(Distance, Distance);

};


Distance operator+(Distance d1, Distance d2)

{

    Distance temp;   

    temp.inch = d1.inch + d2.inch;

    temp.feet  = d1.feet + d2.feet + (temp.inch/12);

    temp.inch = temp.inch%12;

    return temp;

}

        

int main()

{

    Distance d1,d2,d3;

    

    cout << "Enter first  distance:" << endl;

    d1.readDistance();

    cout << endl;

    

    cout << "Enter second distance:" << endl;

    d2.readDistance();

    cout << endl;

     

    d3=d1+d2;

     

    cout << "The sum of two distance is:" << endl;

    d3.displayDistance();

 

    return 0;

}