This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, February 17, 2023

Mention rules for overloading an operator. Write a program to convert class type of data into basic type.

 Rules for overloading an operator:

  1. The operator being overloaded should have at least one operand of a user-defined data type.
  2. Overloaded operators must either be a member function or a friend function of the class.
  3. Overloaded operators must follow the same syntax and precedence rules as the built-in operators.
  4. Overloaded operators cannot change the number of operands, their types, or their intrinsic meanings.
  5. Some operators, such as the conditional and the assignment operators, can be overloaded as member functions and as friend functions, but others, such as the scope resolution operator and the conditional operator, can only be overloaded as member functions.
Program to convert class type of data into basic type:

#include <iostream>
using namespace std;

class Distance {
private:
    int feet;
    float inches;

public:
    Distance() {
        feet = 0;
        inches = 0.0;
    }

    Distance(int ft, float in) {
        feet = ft;
        inches = in;
    }

    void showDist() {
        cout << feet << " feet " << inches << " inches" << endl;
    }

    operator float() {
        return (feet + inches / 12.0);
    }
};

int main() {
    Distance d1(5, 10.0);
    float d2;

    d2 = d1;

    cout << "Distance in feet: ";
    d1.showDist();
    cout << "Distance in meters: " << d2 << " meters" << endl;

    return 0;
}

In this program, the "Distance" class has a conversion operator 'operator float()', which allows an object of the "Distance" class to be converted to a float value. The 'd1' object of the "Distance" class is assigned to the "d2" variable of the 'float' data type, which invokes the conversion operator. The "showDist()" function displays the distance in feet and inches, and the "d2" variable is displayed as the distance in meters.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget