Overload Built-in Conversion, Conversion from a user-defined data type to a built-in data type - C++ Class

C++ examples for Class:Operator Overload

Introduction

The following code implements cast from Date class to long.

Demo Code

                                                                                                     
#include <iostream>
#include <iomanip>
using namespace std;
// declaration section
class Date/*  w ww.ja va  2  s  .com*/
{
   private:
   int month, day, year;
   public:
   Date(int = 7, int = 4, int = 2012);    // constructor
   operator long();     // conversion operator prototype
   void showDate();
};
// implementation section
Date::Date(int mm, int dd, int yyyy) // constructor
{
   month = mm;
   day = dd;
   year = yyyy;
}
// conversion operator definition for converting a Date to a long int
Date::operator long()   // must return a long, as its name implies
{
   long yyyymmdd;
   yyyymmdd = year * 10000 + month * 100 + day;
   return(yyyymmdd);
}
// member function to display a date
void Date::showDate()
{
   cout << setfill('0') << setw(2) << month << '/' << setw(2) << day << '/' << setw(2) << year % 100;
   return;
}
int main()
{
   Date a(4,1,2012);  // declare and initialize one object of type Date
   long b;            // declare an object of type long
   b = long(a);       // call the conversion function
   cout << "a's date is ";
   a.showDate();
   cout << "\nThis date, as a long integer, is " << b << endl;
   return 0;
}

Result


Related Tutorials