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.

Wednesday, March 1, 2023

What are the different types of type conversion possible in operator overloading? Write a program showing the example of basic class type conversion.

 In operator overloading, the following types of type conversion are possible:

  1. Basic type conversion - This involves conversion of one basic data type to another. For example, converting an integer to a float.
  2. Class type conversion - This involves conversion of an object of one class type to an object of another class type.

Here is an example program showing the basic class type conversion:

#include<iostream>
using namespace std;
class Distance {
   private:
      int feet;
      int inches;
   public:
      Distance() {
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i) {
         feet = f;
         inches = i;
      }
      operator int() {
         return feet;
      }
};
int main() {
   Distance d1(10, 6);
   int feet;
   feet = d1;
   cout << "Feet : " << feet << endl;
   return 0;
}

In the above program, a class named Distance is defined with two private data members feet and inches. The class also has two constructors, one with no arguments and another with two integer arguments to initialize the data members. The class also has a conversion operator of type int, which converts an object of type Distance to an integer, by returning the value of feet.

In the main function, an object d1 of type Distance is created and initialized to 10 feet and 6 inches. The object is then assigned to an integer variable feet using the conversion operator, and the value of feet is printed.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget