Use of explicit keyword in C++

C++Server Side ProgrammingProgramming

Here we will see what will be the effect of explicit keyword in C++. Before discussing that, let us see one example code, and try to find out its output.

Example

#include <iostream>
using namespace std;
class Point {
   private:
      double x, y;
   public:
      Point(double a = 0.0, double b = 0.0) : x(a), y(b) {
         //constructor
      }
      bool operator==(Point p2) {
         if(p2.x == this->x && p2.y == this->y)
         return true;
         return false;
      }
};
int main() {
   Point p(5, 0);
   if(p == 5)
      cout << "They are same";
   else
      cout << "They are not same";
}

Output

They are same

This is working fine because we know that if one constructor can be called using one argument only, then it will be converted into conversion constructor. But we can avoid this kind of conversion, as this may generate some unreliable results.

To restrict this conversion, we can use the explicit modifier with the constructor. In that case, it will not be converted. If the above program is used using explicit keyword, then it will generate compilation error.

Example

#include <iostream>
using namespace std;
class Point {
   private:
      double x, y;
   public:
      explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) {
         //constructor
      }
      bool operator==(Point p2) {
         if(p2.x == this->x && p2.y == this->y)
         return true;
         return false;
      }
};
int main() {
   Point p(5, 0);
   if(p == 5)
      cout << "They are same";
   else
      cout << "They are not same";
}

Output

[Error] no match for 'operator==' (operand types are 'Point' and 'int')
[Note] candidates are:
[Note] bool Point::operator==(Point)

We can still typecast a value to the Point type by using explicit casting.

Example

#include <iostream>
using namespace std;
class Point {
   private:
      double x, y;
   public:
      explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) {
         //constructor
      }
      bool operator==(Point p2) {
         if(p2.x == this->x && p2.y == this->y)
         return true;
         return false;
      }
};
int main() {
   Point p(5, 0);
   if(p == (Point)5)
      cout << "They are same";
   else
      cout << "They are not same";
}

Output

They are same
raja
Published on 08-May-2019 09:24:13
Advertisements