Create Explicit one-arg constructor - C++ Class

C++ examples for Class:Constructor

Description

Create Explicit one-arg constructor

Demo Code

#include <iostream>
using namespace std;
class Measure//from   ww  w .j  a  va2 s.  co m
{
   private:
       const float MTF;          //meters to feet
       int feet;
       float inches;
   public:                      //no-args constructor
   Measure() : feet(0), inches(0.0), MTF(3.280833F)
   {  }
   //EXPLICIT one-arg constructor
   explicit Measure(float meters) : MTF(3.280833F)
   {
      float fltfeet = MTF * meters;
      feet = int(fltfeet);
      inches = 12*(fltfeet-feet);
   }
   void showdist()
   { cout << feet << "\'-" << inches << '\"'; }
};
int main()
{
   void fancyDist(Measure);    //declaration
   Measure dist1(2.35F);       //uses 1-arg constructor to convert meters to Measure
   // Measure dist1 = 2.35F;      //ERROR if ctor is explicit
   cout << "\ndist1 = "; dist1.showdist();
   float mtrs = 3.0F;
   cout << "\ndist1 ";
   // fancyDist(mtrs);             //ERROR if ctor is explicit
   return 0;
}
void fancyDist(Measure d)
{
   cout << "(in feet and inches) = ";
   d.showdist();
   cout << endl;
}

Result


Related Tutorials