Programming‎ > ‎C++‎ > ‎Programming Tips‎ > ‎Misc‎ > ‎

Explicit Constructor

Constructors declared explicit are usually preferable to non-explicit once, because they prevent compilers from performing unexpected (often unintended) type conversions. Unless I have a good reason for allowing a constructor to be used for implicit type conversions, I declare it explicit. I encourage you to follow the same policy.

 
#include <cstdlib>
#include <iostream>
using namespace std;
class MyClass
{
  private:
    int m_paramInt;
    bool m_paramBool;
  public:
    explicit MyClass(int x = 0, bool b = true)   // default constructor, can be called without any argumrnts
    {
      m_paramInt = x;
      m_paramBool = b;        
    }
   
    void printAll();
};
 
void MyClass::printAll()
{
     std::cout << "\n " << m_paramInt << "   " << m_paramBool;
}
 
void doSomeThing(MyClass explicitObject)
{
     explicitObject.printAll();
}
 
int main(int argc, char *argv[])
{
    MyClass b1;       // fine, both arguments are default
    b1.printAll();      // 0 1
   
    MyClass b2(28);  // fine, second argument is default
    b2.printAll();       // 28 1
   
    doSomeThing(b1); // fine, passes a MyClass to doSomeThing
                             // 0 1
   
    doSomeThing(MyClass(25)); // fine, passes a MyClass to doSomeThing
                                          // 25 1
   
    #if 0
    doSomeThing(30); // error!, doSomeThing takes a Myclass, not an int, 
                             //         and there is no implicit conversion from int to Myclass
                             // fine, if explicit is removed from MyClass constructor
                             // 30 1
    #endif
   
    system("PAUSE");
    return EXIT_SUCCESS;
}
Comments