C++ examples for Class:Constructor
Adds the explicit modifier to the myclass constructor:
#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; }