Adds the explicit modifier to the myclass constructor: - C++ Class

C++ examples for Class:Constructor

Description

Adds the explicit modifier to the myclass constructor:

Demo Code

#include <iostream>
using namespace std;
class myclass {/*from w  ww  . j  a v a 2s  .  c  om*/
   int val;
   public:
   // Now myclass(int) is explicit.
   explicit myclass(int x) { val = x; }
   int getval() { return val; }
};
int main()
{
   myclass ob(4); // Still OK
   cout << "val in ob: " << ob.getval() << endl;
   // the implicit conversion from int to myclass is no longer allowed.
   //myclass ob2 = 19;  // Error!
   //cout << "val in ob2: " << ob.getval() << endl;
   return 0;
}

Result


Related Tutorials