conversion from basic to user-defined


Conversion from Basic to User-Defined variable

Consider the following example.

class Distance

                 {

                  public  : 

                                Distance(void)    // Constructor with no

                                 {                                               // argument

                                                   feet = 0;

                                                   inches = 0.0;

                                                 };

 

                                                Distance(float metres)

                                                 {

                                                   float f;                                     // Constructor with

                                                   f = 3.28 * metres;      // one argument

                                                   feet = int(f);         // also used for                          

                                                   inches = 12 * ( f - feet);// conversion                                             };

                                                                                void display(void)

                                                 {

                                                   cout << " Feet = " << feet <<",";

                                                   cout << " Inches = " << inches << endl;

                                                 };

  private :            

int feet;

float inches;

 };

void main (void)

                {

                   Distance d1 = 1.25;  // Uses 2nd constructor

                   Distance d2;                      // Uses 1st constructor 

                   float m;

        d2 = 2.0 ;             // Uses 2nd constructor

                   cout << " 1.25 metres is : " << d1.showdist() ;

                   cout << " 2.0  metres is :" << d2.showdist();

     }

Output :

                                1.25 metres is :FEET = 4 , INCHES = 1.199999        

                                2.0  metres is :FEET = 6 , INCHES = 6.719999         

The above program changes distance in metres ( basic data type) into feet and inches ( members of an object of class Distance ).

The declaration of first object d1 uses the second constructor and conversion takes place. Though, when the statement encountered is

d2 = 2.0;

The compiler first checks for an operator function for the assignment operator. If the assignment operator is not overloaded, then it uses the constructor to do the conversion.

 

 

Request for Solution File

Ask an Expert for Answer!!
C/C++ Programming: conversion from basic to user-defined
Reference No:- TGS0309403

Expected delivery within 24 Hours