Discussion on C++ Explicit Constructors of explicit constructor

  • 2020-05-12 02:53:08
  • OfStack

C++ provides many default functions for classes (Class). If you don't declare it yourself, the compiler will give you an copy constructor, an copy assignment operator, and a destructor. In addition, if no constructor is declared, the compiler will declare an default constructor for us. Much like the Empty class below:


class Empty{
  public:
    Empty();
    Empty(const Empty &rhs);
    ~Empty();
    Empty& operator=(const Empty &rhs);
};

As Effective C++ says, if you don't want to use a function automatically generated by the compiler, you should explicitly reject it.

1. Implicit constructor in C++

If one of the constructors of the c++ class has one argument, there is a default conversion operation at compile time: convert the data of the corresponding data type of the constructor to the class object.

2.Explicit Constructors explicit constructor

To avoid the default conversion operation for the one-argument constructor mentioned above, use the Explicit keyword before the constructor.

3. The following examples:


#include <iostream>
using namespace std;
class B{
  public:
    int data;
    B(int _data):data(_data){}
    //explicit B(int _data):data(_data){}
};

int main(){
  B temp=5;
  cout<<temp.data<<endl;
  return 0;
}

Line 11 of the program converts int to an object of type B, using an implicit constructor. Because there is a constructor in B with only one parameter, and the parameter type is also int.

If you prefix the constructor with explicit to show the constructor, line 11 will not compile. Because at this point, there's no implicit constructor.


Related articles: