Explicit conversion constructor

Consider an example below to understand the concept of explicit constructor

#include <iostream>
using namespace std;

class person {
private:
unsigned int m_age;
char m_gender;
public:
person (unsigned int age = 40, char gender = ‘M’);
bool operator==(const person& other) {
cout << "Comparison"<< endl;
if ((other.m_age == m_age) && (other.m_gender == m_gender)) {
return true;
}
return false;
}
};

person::person(unsigned int age, char gender)
{
cout << "C'tor" << endl;
m_age = age;
m_gender = gender;
}

int main() {
person p(40, ‘M’);
person p1 = 40; //Implicit conversion
if ( p == 40) { //Implicit conversion
cout << “Person age is 40” << endl;
}
return 0;
}

Output:
C’tor
C’tor
C’tor
Comparison
Person age is 40

If class has constructor with one argument, then compiler performs the implicit conversion.
In the 2nd line of main, we are assigning 40 to p1. Ideally, this should not compiled because this is not how we create an object. However, compiler try to implicitly convert in to an object with argument as 40 which works as per the constructor. Similarly for 3rd Line as well. Compiler will create an temporary object for 40 and then call comparison operator==. Such constructor is called conversion constructor
This is clear from the output as well.

To avoid such scenarios, we can make conversion constructor an explicit conversion constructor like below:

explicit person (unsigned int age = 40, char gender = ‘M’);

With this change, above code will not compiled because now no implicit conversion will happen by compiler.

NOTE:

  • This implicit conversion will happen on the first constructor argument. If you try to do the below without using explicit constructor, then it will not pass and there will be no error also.
      if (p == ‘M’) {
  cout  << “ This code will not hit since gender is constructor second argumnent " << end;
      }
  • explicit specifier is required only in declaration.

Related posts