Explicit keyword in C++

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

2 Responses to Explicit keyword in C++

  1. cppkid says:

    Hi,
    thanks a lot for posting the comment. Could you please translate it to English so that many people (including me) can understand?

    Thanks and regards,
    Shibu kumar K.B.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: