Explicit keyword in C++

July 2, 2008

In C++, constructors can do implicit type conversion. For example,

class MyClass
{
public:
   MyClass(int No)
   {
      m_No = No;
   }
private:
   int m_No;
};

void MyFunction(MyClass myClass)
{
}

Now, if I make a declaration

MyClass myClass = 77, it will work perfectly, as C++ implicitly calls the constructor as

MyClass myClass = MyClass(77), which is quite a valid statement. Same is the case if I call MyFunction(77).

Such a constructor is called a converting constructor.

However, this can be confusing, and should be avoided as a better coding practice.

C++ offers a way to avoid such converting constructors using the keyword explicit. So the constructor can be declared as

public:
explicit MyClass(int No)
{
   m_No = No;
}

Now see the following statements.

MyClass myClass(77); // Legal

MyClass myClas = 77; // Illegal

MyClass myClass = MyClass(77); // Legal

MyClass myClass;

myClass = 77; // Illegal

MyFunction(MyClass(77)); // Legal

MyFunction(77); // Illegal

Advertisements