C++ program for type casting from one user-defined type to another user-defined type

//C++ program to convert an object of Feet class into object of Meter class
//Feet has ft and in as data members
//Meter has m and cm as data members
//Conversion Routine in Source Object

#include <iostream>
using namespace std;
class Meter
{
    private:
        int m;
        float cm;
    public:
        Meter()
        {
            m=cm=0;
        }
        Meter(int meter,float centimeter)
        {
            m=meter;
            cm=centimeter;
        }
        void display()
        {
            cout<<m<<"m "<<cm<<"cm."<<endl;
        }
};
class Feet
{
    private:
        int ft,in;
    public:
        Feet()
        {
            ft=in=0;
        }
        Feet(int feet,int inch)
        {
            ft=feet;
            in=inch;
        }
        void display()
        {
            cout<<ft<<"ft "<<in<<"in."<<endl;
        }
        operator Meter()
//casting operator function is in source object here
        {
            int m;
            float cm,total_m;
            total_m=(ft+in/12.0)/3.33;
            m=(int)total_m;
            cm=(total_m - m)*100;
            return Meter(m,cm); //temporary object
         }
};
int main()
{
    Feet f(12,6);
    f.display();
    Meter m;
    m=f;
    m.display();
    return 0;
}

No comments:

Post a Comment